1 //===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- C++ -*-===// 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 class for OpenMP runtime code generation. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H 14 #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H 15 16 #include "CGValue.h" 17 #include "clang/AST/DeclOpenMP.h" 18 #include "clang/AST/GlobalDecl.h" 19 #include "clang/AST/Type.h" 20 #include "clang/Basic/OpenMPKinds.h" 21 #include "clang/Basic/SourceLocation.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/PointerIntPair.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/StringMap.h" 26 #include "llvm/ADT/StringSet.h" 27 #include "llvm/Frontend/OpenMP/OMPConstants.h" 28 #include "llvm/IR/Function.h" 29 #include "llvm/IR/ValueHandle.h" 30 #include "llvm/Support/AtomicOrdering.h" 31 32 namespace llvm { 33 class ArrayType; 34 class Constant; 35 class FunctionType; 36 class GlobalVariable; 37 class StructType; 38 class Type; 39 class Value; 40 } // namespace llvm 41 42 namespace clang { 43 class Expr; 44 class OMPDependClause; 45 class OMPExecutableDirective; 46 class OMPLoopDirective; 47 class VarDecl; 48 class OMPDeclareReductionDecl; 49 class IdentifierInfo; 50 51 namespace CodeGen { 52 class Address; 53 class CodeGenFunction; 54 class CodeGenModule; 55 56 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP 57 /// region. 58 class PrePostActionTy { 59 public: 60 explicit PrePostActionTy() {} 61 virtual void Enter(CodeGenFunction &CGF) {} 62 virtual void Exit(CodeGenFunction &CGF) {} 63 virtual ~PrePostActionTy() {} 64 }; 65 66 /// Class provides a way to call simple version of codegen for OpenMP region, or 67 /// an advanced with possible pre|post-actions in codegen. 68 class RegionCodeGenTy final { 69 intptr_t CodeGen; 70 typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &); 71 CodeGenTy Callback; 72 mutable PrePostActionTy *PrePostAction; 73 RegionCodeGenTy() = delete; 74 RegionCodeGenTy &operator=(const RegionCodeGenTy &) = delete; 75 template <typename Callable> 76 static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF, 77 PrePostActionTy &Action) { 78 return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action); 79 } 80 81 public: 82 template <typename Callable> 83 RegionCodeGenTy( 84 Callable &&CodeGen, 85 std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>, 86 RegionCodeGenTy>::value> * = nullptr) 87 : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)), 88 Callback(CallbackFn<std::remove_reference_t<Callable>>), 89 PrePostAction(nullptr) {} 90 void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; } 91 void operator()(CodeGenFunction &CGF) const; 92 }; 93 94 struct OMPTaskDataTy final { 95 SmallVector<const Expr *, 4> PrivateVars; 96 SmallVector<const Expr *, 4> PrivateCopies; 97 SmallVector<const Expr *, 4> FirstprivateVars; 98 SmallVector<const Expr *, 4> FirstprivateCopies; 99 SmallVector<const Expr *, 4> FirstprivateInits; 100 SmallVector<const Expr *, 4> LastprivateVars; 101 SmallVector<const Expr *, 4> LastprivateCopies; 102 SmallVector<const Expr *, 4> ReductionVars; 103 SmallVector<const Expr *, 4> ReductionCopies; 104 SmallVector<const Expr *, 4> ReductionOps; 105 struct DependData { 106 OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; 107 const Expr *IteratorExpr = nullptr; 108 SmallVector<const Expr *, 4> DepExprs; 109 explicit DependData() = default; 110 DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr) 111 : DepKind(DepKind), IteratorExpr(IteratorExpr) {} 112 }; 113 SmallVector<DependData, 4> Dependences; 114 llvm::PointerIntPair<llvm::Value *, 1, bool> Final; 115 llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule; 116 llvm::PointerIntPair<llvm::Value *, 1, bool> Priority; 117 llvm::Value *Reductions = nullptr; 118 unsigned NumberOfParts = 0; 119 bool Tied = true; 120 bool Nogroup = false; 121 }; 122 123 /// Class intended to support codegen of all kind of the reduction clauses. 124 class ReductionCodeGen { 125 private: 126 /// Data required for codegen of reduction clauses. 127 struct ReductionData { 128 /// Reference to the item shared between tasks to reduce into. 129 const Expr *Shared = nullptr; 130 /// Reference to the original item. 131 const Expr *Ref = nullptr; 132 /// Helper expression for generation of private copy. 133 const Expr *Private = nullptr; 134 /// Helper expression for generation reduction operation. 135 const Expr *ReductionOp = nullptr; 136 ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private, 137 const Expr *ReductionOp) 138 : Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) { 139 } 140 }; 141 /// List of reduction-based clauses. 142 SmallVector<ReductionData, 4> ClausesData; 143 144 /// List of addresses of shared variables/expressions. 145 SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses; 146 /// List of addresses of original variables/expressions. 147 SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses; 148 /// Sizes of the reduction items in chars. 149 SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes; 150 /// Base declarations for the reduction items. 151 SmallVector<const VarDecl *, 4> BaseDecls; 152 153 /// Emits lvalue for shared expression. 154 LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E); 155 /// Emits upper bound for shared expression (if array section). 156 LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E); 157 /// Performs aggregate initialization. 158 /// \param N Number of reduction item in the common list. 159 /// \param PrivateAddr Address of the corresponding private item. 160 /// \param SharedLVal Address of the original shared variable. 161 /// \param DRD Declare reduction construct used for reduction item. 162 void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N, 163 Address PrivateAddr, LValue SharedLVal, 164 const OMPDeclareReductionDecl *DRD); 165 166 public: 167 ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs, 168 ArrayRef<const Expr *> Privates, 169 ArrayRef<const Expr *> ReductionOps); 170 /// Emits lvalue for the shared and original reduction item. 171 /// \param N Number of the reduction item. 172 void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N); 173 /// Emits the code for the variable-modified type, if required. 174 /// \param N Number of the reduction item. 175 void emitAggregateType(CodeGenFunction &CGF, unsigned N); 176 /// Emits the code for the variable-modified type, if required. 177 /// \param N Number of the reduction item. 178 /// \param Size Size of the type in chars. 179 void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size); 180 /// Performs initialization of the private copy for the reduction item. 181 /// \param N Number of the reduction item. 182 /// \param PrivateAddr Address of the corresponding private item. 183 /// \param DefaultInit Default initialization sequence that should be 184 /// performed if no reduction specific initialization is found. 185 /// \param SharedLVal Address of the original shared variable. 186 void 187 emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, 188 LValue SharedLVal, 189 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit); 190 /// Returns true if the private copy requires cleanups. 191 bool needCleanups(unsigned N); 192 /// Emits cleanup code for the reduction item. 193 /// \param N Number of the reduction item. 194 /// \param PrivateAddr Address of the corresponding private item. 195 void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); 196 /// Adjusts \p PrivatedAddr for using instead of the original variable 197 /// address in normal operations. 198 /// \param N Number of the reduction item. 199 /// \param PrivateAddr Address of the corresponding private item. 200 Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, 201 Address PrivateAddr); 202 /// Returns LValue for the reduction item. 203 LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; } 204 /// Returns LValue for the original reduction item. 205 LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; } 206 /// Returns the size of the reduction item (in chars and total number of 207 /// elements in the item), or nullptr, if the size is a constant. 208 std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const { 209 return Sizes[N]; 210 } 211 /// Returns the base declaration of the reduction item. 212 const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; } 213 /// Returns the base declaration of the reduction item. 214 const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; } 215 /// Returns true if the initialization of the reduction item uses initializer 216 /// from declare reduction construct. 217 bool usesReductionInitializer(unsigned N) const; 218 }; 219 220 class CGOpenMPRuntime { 221 public: 222 /// Allows to disable automatic handling of functions used in target regions 223 /// as those marked as `omp declare target`. 224 class DisableAutoDeclareTargetRAII { 225 CodeGenModule &CGM; 226 bool SavedShouldMarkAsGlobal; 227 228 public: 229 DisableAutoDeclareTargetRAII(CodeGenModule &CGM); 230 ~DisableAutoDeclareTargetRAII(); 231 }; 232 233 /// Manages list of nontemporal decls for the specified directive. 234 class NontemporalDeclsRAII { 235 CodeGenModule &CGM; 236 const bool NeedToPush; 237 238 public: 239 NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S); 240 ~NontemporalDeclsRAII(); 241 }; 242 243 /// Maps the expression for the lastprivate variable to the global copy used 244 /// to store new value because original variables are not mapped in inner 245 /// parallel regions. Only private copies are captured but we need also to 246 /// store private copy in shared address. 247 /// Also, stores the expression for the private loop counter and it 248 /// threaprivate name. 249 struct LastprivateConditionalData { 250 llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>> 251 DeclToUniqueName; 252 LValue IVLVal; 253 llvm::Function *Fn = nullptr; 254 bool Disabled = false; 255 }; 256 /// Manages list of lastprivate conditional decls for the specified directive. 257 class LastprivateConditionalRAII { 258 enum class ActionToDo { 259 DoNotPush, 260 PushAsLastprivateConditional, 261 DisableLastprivateConditional, 262 }; 263 CodeGenModule &CGM; 264 ActionToDo Action = ActionToDo::DoNotPush; 265 266 /// Check and try to disable analysis of inner regions for changes in 267 /// lastprivate conditional. 268 void tryToDisableInnerAnalysis(const OMPExecutableDirective &S, 269 llvm::DenseSet<CanonicalDeclPtr<const Decl>> 270 &NeedToAddForLPCsAsDisabled) const; 271 272 LastprivateConditionalRAII(CodeGenFunction &CGF, 273 const OMPExecutableDirective &S); 274 275 public: 276 explicit LastprivateConditionalRAII(CodeGenFunction &CGF, 277 const OMPExecutableDirective &S, 278 LValue IVLVal); 279 static LastprivateConditionalRAII disable(CodeGenFunction &CGF, 280 const OMPExecutableDirective &S); 281 ~LastprivateConditionalRAII(); 282 }; 283 284 protected: 285 CodeGenModule &CGM; 286 StringRef FirstSeparator, Separator; 287 288 /// Constructor allowing to redefine the name separator for the variables. 289 explicit CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator, 290 StringRef Separator); 291 292 /// Creates offloading entry for the provided entry ID \a ID, 293 /// address \a Addr, size \a Size, and flags \a Flags. 294 virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr, 295 uint64_t Size, int32_t Flags, 296 llvm::GlobalValue::LinkageTypes Linkage); 297 298 /// Helper to emit outlined function for 'target' directive. 299 /// \param D Directive to emit. 300 /// \param ParentName Name of the function that encloses the target region. 301 /// \param OutlinedFn Outlined function value to be defined by this call. 302 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 303 /// \param IsOffloadEntry True if the outlined function is an offload entry. 304 /// \param CodeGen Lambda codegen specific to an accelerator device. 305 /// An outlined function may not be an entry if, e.g. the if clause always 306 /// evaluates to false. 307 virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, 308 StringRef ParentName, 309 llvm::Function *&OutlinedFn, 310 llvm::Constant *&OutlinedFnID, 311 bool IsOffloadEntry, 312 const RegionCodeGenTy &CodeGen); 313 314 /// Emits object of ident_t type with info for source location. 315 /// \param Flags Flags for OpenMP location. 316 /// 317 llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, 318 unsigned Flags = 0); 319 320 /// Returns pointer to ident_t type. 321 llvm::Type *getIdentTyPointerTy(); 322 323 /// Gets thread id value for the current thread. 324 /// 325 llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc); 326 327 /// Get the function name of an outlined region. 328 // The name can be customized depending on the target. 329 // 330 virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; } 331 332 /// Emits \p Callee function call with arguments \p Args with location \p Loc. 333 void emitCall(CodeGenFunction &CGF, SourceLocation Loc, 334 llvm::FunctionCallee Callee, 335 ArrayRef<llvm::Value *> Args = llvm::None) const; 336 337 /// Emits address of the word in a memory where current thread id is 338 /// stored. 339 virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc); 340 341 void setLocThreadIdInsertPt(CodeGenFunction &CGF, 342 bool AtCurrentPoint = false); 343 void clearLocThreadIdInsertPt(CodeGenFunction &CGF); 344 345 /// Check if the default location must be constant. 346 /// Default is false to support OMPT/OMPD. 347 virtual bool isDefaultLocationConstant() const { return false; } 348 349 /// Returns additional flags that can be stored in reserved_2 field of the 350 /// default location. 351 virtual unsigned getDefaultLocationReserved2Flags() const { return 0; } 352 353 /// Returns default flags for the barriers depending on the directive, for 354 /// which this barier is going to be emitted. 355 static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind); 356 357 /// Get the LLVM type for the critical name. 358 llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;} 359 360 /// Returns corresponding lock object for the specified critical region 361 /// name. If the lock object does not exist it is created, otherwise the 362 /// reference to the existing copy is returned. 363 /// \param CriticalName Name of the critical region. 364 /// 365 llvm::Value *getCriticalRegionLock(StringRef CriticalName); 366 367 private: 368 /// Default const ident_t object used for initialization of all other 369 /// ident_t objects. 370 llvm::Constant *DefaultOpenMPPSource = nullptr; 371 using FlagsTy = std::pair<unsigned, unsigned>; 372 /// Map of flags and corresponding default locations. 373 using OpenMPDefaultLocMapTy = llvm::DenseMap<FlagsTy, llvm::Value *>; 374 OpenMPDefaultLocMapTy OpenMPDefaultLocMap; 375 Address getOrCreateDefaultLocation(unsigned Flags); 376 377 QualType IdentQTy; 378 llvm::StructType *IdentTy = nullptr; 379 /// Map for SourceLocation and OpenMP runtime library debug locations. 380 typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDebugLocMapTy; 381 OpenMPDebugLocMapTy OpenMPDebugLocMap; 382 /// The type for a microtask which gets passed to __kmpc_fork_call(). 383 /// Original representation is: 384 /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...); 385 llvm::FunctionType *Kmpc_MicroTy = nullptr; 386 /// Stores debug location and ThreadID for the function. 387 struct DebugLocThreadIdTy { 388 llvm::Value *DebugLoc; 389 llvm::Value *ThreadID; 390 /// Insert point for the service instructions. 391 llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr; 392 }; 393 /// Map of local debug location, ThreadId and functions. 394 typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy> 395 OpenMPLocThreadIDMapTy; 396 OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap; 397 /// Map of UDRs and corresponding combiner/initializer. 398 typedef llvm::DenseMap<const OMPDeclareReductionDecl *, 399 std::pair<llvm::Function *, llvm::Function *>> 400 UDRMapTy; 401 UDRMapTy UDRMap; 402 /// Map of functions and locally defined UDRs. 403 typedef llvm::DenseMap<llvm::Function *, 404 SmallVector<const OMPDeclareReductionDecl *, 4>> 405 FunctionUDRMapTy; 406 FunctionUDRMapTy FunctionUDRMap; 407 /// Map from the user-defined mapper declaration to its corresponding 408 /// functions. 409 llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap; 410 /// Map of functions and their local user-defined mappers. 411 using FunctionUDMMapTy = 412 llvm::DenseMap<llvm::Function *, 413 SmallVector<const OMPDeclareMapperDecl *, 4>>; 414 FunctionUDMMapTy FunctionUDMMap; 415 /// Maps local variables marked as lastprivate conditional to their internal 416 /// types. 417 llvm::DenseMap<llvm::Function *, 418 llvm::DenseMap<CanonicalDeclPtr<const Decl>, 419 std::tuple<QualType, const FieldDecl *, 420 const FieldDecl *, LValue>>> 421 LastprivateConditionalToTypes; 422 /// Type kmp_critical_name, originally defined as typedef kmp_int32 423 /// kmp_critical_name[8]; 424 llvm::ArrayType *KmpCriticalNameTy; 425 /// An ordered map of auto-generated variables to their unique names. 426 /// It stores variables with the following names: 1) ".gomp_critical_user_" + 427 /// <critical_section_name> + ".var" for "omp critical" directives; 2) 428 /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate 429 /// variables. 430 llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator> 431 InternalVars; 432 /// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); 433 llvm::Type *KmpRoutineEntryPtrTy = nullptr; 434 QualType KmpRoutineEntryPtrQTy; 435 /// Type typedef struct kmp_task { 436 /// void * shareds; /**< pointer to block of pointers to 437 /// shared vars */ 438 /// kmp_routine_entry_t routine; /**< pointer to routine to call for 439 /// executing task */ 440 /// kmp_int32 part_id; /**< part id for the task */ 441 /// kmp_routine_entry_t destructors; /* pointer to function to invoke 442 /// deconstructors of firstprivate C++ objects */ 443 /// } kmp_task_t; 444 QualType KmpTaskTQTy; 445 /// Saved kmp_task_t for task directive. 446 QualType SavedKmpTaskTQTy; 447 /// Saved kmp_task_t for taskloop-based directive. 448 QualType SavedKmpTaskloopTQTy; 449 /// Type typedef struct kmp_depend_info { 450 /// kmp_intptr_t base_addr; 451 /// size_t len; 452 /// struct { 453 /// bool in:1; 454 /// bool out:1; 455 /// } flags; 456 /// } kmp_depend_info_t; 457 QualType KmpDependInfoTy; 458 /// struct kmp_dim { // loop bounds info casted to kmp_int64 459 /// kmp_int64 lo; // lower 460 /// kmp_int64 up; // upper 461 /// kmp_int64 st; // stride 462 /// }; 463 QualType KmpDimTy; 464 /// Type struct __tgt_offload_entry{ 465 /// void *addr; // Pointer to the offload entry info. 466 /// // (function or global) 467 /// char *name; // Name of the function or global. 468 /// size_t size; // Size of the entry info (0 if it a function). 469 /// int32_t flags; 470 /// int32_t reserved; 471 /// }; 472 QualType TgtOffloadEntryQTy; 473 /// Entity that registers the offloading constants that were emitted so 474 /// far. 475 class OffloadEntriesInfoManagerTy { 476 CodeGenModule &CGM; 477 478 /// Number of entries registered so far. 479 unsigned OffloadingEntriesNum = 0; 480 481 public: 482 /// Base class of the entries info. 483 class OffloadEntryInfo { 484 public: 485 /// Kind of a given entry. 486 enum OffloadingEntryInfoKinds : unsigned { 487 /// Entry is a target region. 488 OffloadingEntryInfoTargetRegion = 0, 489 /// Entry is a declare target variable. 490 OffloadingEntryInfoDeviceGlobalVar = 1, 491 /// Invalid entry info. 492 OffloadingEntryInfoInvalid = ~0u 493 }; 494 495 protected: 496 OffloadEntryInfo() = delete; 497 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {} 498 explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, 499 uint32_t Flags) 500 : Flags(Flags), Order(Order), Kind(Kind) {} 501 ~OffloadEntryInfo() = default; 502 503 public: 504 bool isValid() const { return Order != ~0u; } 505 unsigned getOrder() const { return Order; } 506 OffloadingEntryInfoKinds getKind() const { return Kind; } 507 uint32_t getFlags() const { return Flags; } 508 void setFlags(uint32_t NewFlags) { Flags = NewFlags; } 509 llvm::Constant *getAddress() const { 510 return cast_or_null<llvm::Constant>(Addr); 511 } 512 void setAddress(llvm::Constant *V) { 513 assert(!Addr.pointsToAliveValue() && "Address has been set before!"); 514 Addr = V; 515 } 516 static bool classof(const OffloadEntryInfo *Info) { return true; } 517 518 private: 519 /// Address of the entity that has to be mapped for offloading. 520 llvm::WeakTrackingVH Addr; 521 522 /// Flags associated with the device global. 523 uint32_t Flags = 0u; 524 525 /// Order this entry was emitted. 526 unsigned Order = ~0u; 527 528 OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid; 529 }; 530 531 /// Return true if a there are no entries defined. 532 bool empty() const; 533 /// Return number of entries defined so far. 534 unsigned size() const { return OffloadingEntriesNum; } 535 OffloadEntriesInfoManagerTy(CodeGenModule &CGM) : CGM(CGM) {} 536 537 // 538 // Target region entries related. 539 // 540 541 /// Kind of the target registry entry. 542 enum OMPTargetRegionEntryKind : uint32_t { 543 /// Mark the entry as target region. 544 OMPTargetRegionEntryTargetRegion = 0x0, 545 /// Mark the entry as a global constructor. 546 OMPTargetRegionEntryCtor = 0x02, 547 /// Mark the entry as a global destructor. 548 OMPTargetRegionEntryDtor = 0x04, 549 }; 550 551 /// Target region entries info. 552 class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo { 553 /// Address that can be used as the ID of the entry. 554 llvm::Constant *ID = nullptr; 555 556 public: 557 OffloadEntryInfoTargetRegion() 558 : OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {} 559 explicit OffloadEntryInfoTargetRegion(unsigned Order, 560 llvm::Constant *Addr, 561 llvm::Constant *ID, 562 OMPTargetRegionEntryKind Flags) 563 : OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags), 564 ID(ID) { 565 setAddress(Addr); 566 } 567 568 llvm::Constant *getID() const { return ID; } 569 void setID(llvm::Constant *V) { 570 assert(!ID && "ID has been set before!"); 571 ID = V; 572 } 573 static bool classof(const OffloadEntryInfo *Info) { 574 return Info->getKind() == OffloadingEntryInfoTargetRegion; 575 } 576 }; 577 578 /// Initialize target region entry. 579 void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 580 StringRef ParentName, unsigned LineNum, 581 unsigned Order); 582 /// Register target region entry. 583 void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 584 StringRef ParentName, unsigned LineNum, 585 llvm::Constant *Addr, llvm::Constant *ID, 586 OMPTargetRegionEntryKind Flags); 587 /// Return true if a target region entry with the provided information 588 /// exists. 589 bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 590 StringRef ParentName, unsigned LineNum) const; 591 /// brief Applies action \a Action on all registered entries. 592 typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned, 593 const OffloadEntryInfoTargetRegion &)> 594 OffloadTargetRegionEntryInfoActTy; 595 void actOnTargetRegionEntriesInfo( 596 const OffloadTargetRegionEntryInfoActTy &Action); 597 598 // 599 // Device global variable entries related. 600 // 601 602 /// Kind of the global variable entry.. 603 enum OMPTargetGlobalVarEntryKind : uint32_t { 604 /// Mark the entry as a to declare target. 605 OMPTargetGlobalVarEntryTo = 0x0, 606 /// Mark the entry as a to declare target link. 607 OMPTargetGlobalVarEntryLink = 0x1, 608 }; 609 610 /// Device global variable entries info. 611 class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo { 612 /// Type of the global variable. 613 CharUnits VarSize; 614 llvm::GlobalValue::LinkageTypes Linkage; 615 616 public: 617 OffloadEntryInfoDeviceGlobalVar() 618 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {} 619 explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, 620 OMPTargetGlobalVarEntryKind Flags) 621 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {} 622 explicit OffloadEntryInfoDeviceGlobalVar( 623 unsigned Order, llvm::Constant *Addr, CharUnits VarSize, 624 OMPTargetGlobalVarEntryKind Flags, 625 llvm::GlobalValue::LinkageTypes Linkage) 626 : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags), 627 VarSize(VarSize), Linkage(Linkage) { 628 setAddress(Addr); 629 } 630 631 CharUnits getVarSize() const { return VarSize; } 632 void setVarSize(CharUnits Size) { VarSize = Size; } 633 llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; } 634 void setLinkage(llvm::GlobalValue::LinkageTypes LT) { Linkage = LT; } 635 static bool classof(const OffloadEntryInfo *Info) { 636 return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar; 637 } 638 }; 639 640 /// Initialize device global variable entry. 641 void initializeDeviceGlobalVarEntryInfo(StringRef Name, 642 OMPTargetGlobalVarEntryKind Flags, 643 unsigned Order); 644 645 /// Register device global variable entry. 646 void 647 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr, 648 CharUnits VarSize, 649 OMPTargetGlobalVarEntryKind Flags, 650 llvm::GlobalValue::LinkageTypes Linkage); 651 /// Checks if the variable with the given name has been registered already. 652 bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const { 653 return OffloadEntriesDeviceGlobalVar.count(VarName) > 0; 654 } 655 /// Applies action \a Action on all registered entries. 656 typedef llvm::function_ref<void(StringRef, 657 const OffloadEntryInfoDeviceGlobalVar &)> 658 OffloadDeviceGlobalVarEntryInfoActTy; 659 void actOnDeviceGlobalVarEntriesInfo( 660 const OffloadDeviceGlobalVarEntryInfoActTy &Action); 661 662 private: 663 // Storage for target region entries kind. The storage is to be indexed by 664 // file ID, device ID, parent function name and line number. 665 typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion> 666 OffloadEntriesTargetRegionPerLine; 667 typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine> 668 OffloadEntriesTargetRegionPerParentName; 669 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName> 670 OffloadEntriesTargetRegionPerFile; 671 typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile> 672 OffloadEntriesTargetRegionPerDevice; 673 typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy; 674 OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion; 675 /// Storage for device global variable entries kind. The storage is to be 676 /// indexed by mangled name. 677 typedef llvm::StringMap<OffloadEntryInfoDeviceGlobalVar> 678 OffloadEntriesDeviceGlobalVarTy; 679 OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar; 680 }; 681 OffloadEntriesInfoManagerTy OffloadEntriesInfoManager; 682 683 bool ShouldMarkAsGlobal = true; 684 /// List of the emitted declarations. 685 llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls; 686 /// List of the global variables with their addresses that should not be 687 /// emitted for the target. 688 llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables; 689 690 /// List of variables that can become declare target implicitly and, thus, 691 /// must be emitted. 692 llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables; 693 694 using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>; 695 /// Stack for list of declarations in current context marked as nontemporal. 696 /// The set is the union of all current stack elements. 697 llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack; 698 699 /// Stack for list of addresses of declarations in current context marked as 700 /// lastprivate conditional. The set is the union of all current stack 701 /// elements. 702 llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack; 703 704 /// Flag for keeping track of weather a requires unified_shared_memory 705 /// directive is present. 706 bool HasRequiresUnifiedSharedMemory = false; 707 708 /// Atomic ordering from the omp requires directive. 709 llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic; 710 711 /// Flag for keeping track of weather a target region has been emitted. 712 bool HasEmittedTargetRegion = false; 713 714 /// Flag for keeping track of weather a device routine has been emitted. 715 /// Device routines are specific to the 716 bool HasEmittedDeclareTargetRegion = false; 717 718 /// Loads all the offload entries information from the host IR 719 /// metadata. 720 void loadOffloadInfoMetadata(); 721 722 /// Returns __tgt_offload_entry type. 723 QualType getTgtOffloadEntryQTy(); 724 725 /// Start scanning from statement \a S and and emit all target regions 726 /// found along the way. 727 /// \param S Starting statement. 728 /// \param ParentName Name of the function declaration that is being scanned. 729 void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName); 730 731 /// Build type kmp_routine_entry_t (if not built yet). 732 void emitKmpRoutineEntryT(QualType KmpInt32Ty); 733 734 /// Returns pointer to kmpc_micro type. 735 llvm::Type *getKmpc_MicroPointerTy(); 736 737 /// Returns specified OpenMP runtime function. 738 /// \param Function OpenMP runtime function. 739 /// \return Specified function. 740 llvm::FunctionCallee createRuntimeFunction(unsigned Function); 741 742 /// Returns __kmpc_for_static_init_* runtime function for the specified 743 /// size \a IVSize and sign \a IVSigned. 744 llvm::FunctionCallee createForStaticInitFunction(unsigned IVSize, 745 bool IVSigned); 746 747 /// Returns __kmpc_dispatch_init_* runtime function for the specified 748 /// size \a IVSize and sign \a IVSigned. 749 llvm::FunctionCallee createDispatchInitFunction(unsigned IVSize, 750 bool IVSigned); 751 752 /// Returns __kmpc_dispatch_next_* runtime function for the specified 753 /// size \a IVSize and sign \a IVSigned. 754 llvm::FunctionCallee createDispatchNextFunction(unsigned IVSize, 755 bool IVSigned); 756 757 /// Returns __kmpc_dispatch_fini_* runtime function for the specified 758 /// size \a IVSize and sign \a IVSigned. 759 llvm::FunctionCallee createDispatchFiniFunction(unsigned IVSize, 760 bool IVSigned); 761 762 /// If the specified mangled name is not in the module, create and 763 /// return threadprivate cache object. This object is a pointer's worth of 764 /// storage that's reserved for use by the OpenMP runtime. 765 /// \param VD Threadprivate variable. 766 /// \return Cache variable for the specified threadprivate. 767 llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD); 768 769 /// Gets (if variable with the given name already exist) or creates 770 /// internal global variable with the specified Name. The created variable has 771 /// linkage CommonLinkage by default and is initialized by null value. 772 /// \param Ty Type of the global variable. If it is exist already the type 773 /// must be the same. 774 /// \param Name Name of the variable. 775 llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty, 776 const llvm::Twine &Name, 777 unsigned AddressSpace = 0); 778 779 /// Set of threadprivate variables with the generated initializer. 780 llvm::StringSet<> ThreadPrivateWithDefinition; 781 782 /// Set of declare target variables with the generated initializer. 783 llvm::StringSet<> DeclareTargetWithDefinition; 784 785 /// Emits initialization code for the threadprivate variables. 786 /// \param VDAddr Address of the global variable \a VD. 787 /// \param Ctor Pointer to a global init function for \a VD. 788 /// \param CopyCtor Pointer to a global copy function for \a VD. 789 /// \param Dtor Pointer to a global destructor function for \a VD. 790 /// \param Loc Location of threadprivate declaration. 791 void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr, 792 llvm::Value *Ctor, llvm::Value *CopyCtor, 793 llvm::Value *Dtor, SourceLocation Loc); 794 795 /// Emit the array initialization or deletion portion for user-defined mapper 796 /// code generation. 797 void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF, 798 llvm::Value *Handle, llvm::Value *BasePtr, 799 llvm::Value *Ptr, llvm::Value *Size, 800 llvm::Value *MapType, CharUnits ElementSize, 801 llvm::BasicBlock *ExitBB, bool IsInit); 802 803 struct TaskResultTy { 804 llvm::Value *NewTask = nullptr; 805 llvm::Function *TaskEntry = nullptr; 806 llvm::Value *NewTaskNewTaskTTy = nullptr; 807 LValue TDBase; 808 const RecordDecl *KmpTaskTQTyRD = nullptr; 809 llvm::Value *TaskDupFn = nullptr; 810 }; 811 /// Emit task region for the task directive. The task region is emitted in 812 /// several steps: 813 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 814 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 815 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 816 /// function: 817 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 818 /// TaskFunction(gtid, tt->part_id, tt->shareds); 819 /// return 0; 820 /// } 821 /// 2. Copy a list of shared variables to field shareds of the resulting 822 /// structure kmp_task_t returned by the previous call (if any). 823 /// 3. Copy a pointer to destructions function to field destructions of the 824 /// resulting structure kmp_task_t. 825 /// \param D Current task directive. 826 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 827 /// /*part_id*/, captured_struct */*__context*/); 828 /// \param SharedsTy A type which contains references the shared variables. 829 /// \param Shareds Context with the list of shared variables from the \p 830 /// TaskFunction. 831 /// \param Data Additional data for task generation like tiednsee, final 832 /// state, list of privates etc. 833 TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, 834 const OMPExecutableDirective &D, 835 llvm::Function *TaskFunction, QualType SharedsTy, 836 Address Shareds, const OMPTaskDataTy &Data); 837 838 /// Returns default address space for the constant firstprivates, 0 by 839 /// default. 840 virtual unsigned getDefaultFirstprivateAddressSpace() const { return 0; } 841 842 /// Emit code that pushes the trip count of loops associated with constructs 843 /// 'target teams distribute' and 'teams distribute parallel for'. 844 /// \param SizeEmitter Emits the int64 value for the number of iterations of 845 /// the associated loop. 846 void emitTargetNumIterationsCall( 847 CodeGenFunction &CGF, const OMPExecutableDirective &D, 848 llvm::Value *DeviceID, 849 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, 850 const OMPLoopDirective &D)> 851 SizeEmitter); 852 853 /// Emit update for lastprivate conditional data. 854 void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal, 855 StringRef UniqueDeclName, LValue LVal, 856 SourceLocation Loc); 857 858 /// Returns the number of the elements and the address of the depobj 859 /// dependency array. 860 /// \return Number of elements in depobj array and the pointer to the array of 861 /// dependencies. 862 std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF, 863 LValue DepobjLVal, 864 SourceLocation Loc); 865 866 public: 867 explicit CGOpenMPRuntime(CodeGenModule &CGM) 868 : CGOpenMPRuntime(CGM, ".", ".") {} 869 virtual ~CGOpenMPRuntime() {} 870 virtual void clear(); 871 872 /// Emits code for OpenMP 'if' clause using specified \a CodeGen 873 /// function. Here is the logic: 874 /// if (Cond) { 875 /// ThenGen(); 876 /// } else { 877 /// ElseGen(); 878 /// } 879 void emitIfClause(CodeGenFunction &CGF, const Expr *Cond, 880 const RegionCodeGenTy &ThenGen, 881 const RegionCodeGenTy &ElseGen); 882 883 /// Checks if the \p Body is the \a CompoundStmt and returns its child 884 /// statement iff there is only one that is not evaluatable at the compile 885 /// time. 886 static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body); 887 888 /// Get the platform-specific name separator. 889 std::string getName(ArrayRef<StringRef> Parts) const; 890 891 /// Emit code for the specified user defined reduction construct. 892 virtual void emitUserDefinedReduction(CodeGenFunction *CGF, 893 const OMPDeclareReductionDecl *D); 894 /// Get combiner/initializer for the specified user-defined reduction, if any. 895 virtual std::pair<llvm::Function *, llvm::Function *> 896 getUserDefinedReduction(const OMPDeclareReductionDecl *D); 897 898 /// Emit the function for the user defined mapper construct. 899 void emitUserDefinedMapper(const OMPDeclareMapperDecl *D, 900 CodeGenFunction *CGF = nullptr); 901 902 /// Emits outlined function for the specified OpenMP parallel directive 903 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 904 /// kmp_int32 BoundID, struct context_vars*). 905 /// \param D OpenMP directive. 906 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 907 /// \param InnermostKind Kind of innermost directive (for simple directives it 908 /// is a directive itself, for combined - its innermost directive). 909 /// \param CodeGen Code generation sequence for the \a D directive. 910 virtual llvm::Function *emitParallelOutlinedFunction( 911 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 912 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); 913 914 /// Emits outlined function for the specified OpenMP teams directive 915 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 916 /// kmp_int32 BoundID, struct context_vars*). 917 /// \param D OpenMP directive. 918 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 919 /// \param InnermostKind Kind of innermost directive (for simple directives it 920 /// is a directive itself, for combined - its innermost directive). 921 /// \param CodeGen Code generation sequence for the \a D directive. 922 virtual llvm::Function *emitTeamsOutlinedFunction( 923 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 924 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); 925 926 /// Emits outlined function for the OpenMP task directive \a D. This 927 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* 928 /// TaskT). 929 /// \param D OpenMP directive. 930 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 931 /// \param PartIDVar Variable for partition id in the current OpenMP untied 932 /// task region. 933 /// \param TaskTVar Variable for task_t argument. 934 /// \param InnermostKind Kind of innermost directive (for simple directives it 935 /// is a directive itself, for combined - its innermost directive). 936 /// \param CodeGen Code generation sequence for the \a D directive. 937 /// \param Tied true if task is generated for tied task, false otherwise. 938 /// \param NumberOfParts Number of parts in untied task. Ignored for tied 939 /// tasks. 940 /// 941 virtual llvm::Function *emitTaskOutlinedFunction( 942 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 943 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 944 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 945 bool Tied, unsigned &NumberOfParts); 946 947 /// Cleans up references to the objects in finished function. 948 /// 949 virtual void functionFinished(CodeGenFunction &CGF); 950 951 /// Emits code for parallel or serial call of the \a OutlinedFn with 952 /// variables captured in a record which address is stored in \a 953 /// CapturedStruct. 954 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of 955 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 956 /// \param CapturedVars A pointer to the record with the references to 957 /// variables used in \a OutlinedFn function. 958 /// \param IfCond Condition in the associated 'if' clause, if it was 959 /// specified, nullptr otherwise. 960 /// 961 virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 962 llvm::Function *OutlinedFn, 963 ArrayRef<llvm::Value *> CapturedVars, 964 const Expr *IfCond); 965 966 /// Emits a critical region. 967 /// \param CriticalName Name of the critical region. 968 /// \param CriticalOpGen Generator for the statement associated with the given 969 /// critical region. 970 /// \param Hint Value of the 'hint' clause (optional). 971 virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, 972 const RegionCodeGenTy &CriticalOpGen, 973 SourceLocation Loc, 974 const Expr *Hint = nullptr); 975 976 /// Emits a master region. 977 /// \param MasterOpGen Generator for the statement associated with the given 978 /// master region. 979 virtual void emitMasterRegion(CodeGenFunction &CGF, 980 const RegionCodeGenTy &MasterOpGen, 981 SourceLocation Loc); 982 983 /// Emits code for a taskyield directive. 984 virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc); 985 986 /// Emit a taskgroup region. 987 /// \param TaskgroupOpGen Generator for the statement associated with the 988 /// given taskgroup region. 989 virtual void emitTaskgroupRegion(CodeGenFunction &CGF, 990 const RegionCodeGenTy &TaskgroupOpGen, 991 SourceLocation Loc); 992 993 /// Emits a single region. 994 /// \param SingleOpGen Generator for the statement associated with the given 995 /// single region. 996 virtual void emitSingleRegion(CodeGenFunction &CGF, 997 const RegionCodeGenTy &SingleOpGen, 998 SourceLocation Loc, 999 ArrayRef<const Expr *> CopyprivateVars, 1000 ArrayRef<const Expr *> DestExprs, 1001 ArrayRef<const Expr *> SrcExprs, 1002 ArrayRef<const Expr *> AssignmentOps); 1003 1004 /// Emit an ordered region. 1005 /// \param OrderedOpGen Generator for the statement associated with the given 1006 /// ordered region. 1007 virtual void emitOrderedRegion(CodeGenFunction &CGF, 1008 const RegionCodeGenTy &OrderedOpGen, 1009 SourceLocation Loc, bool IsThreads); 1010 1011 /// Emit an implicit/explicit barrier for OpenMP threads. 1012 /// \param Kind Directive for which this implicit barrier call must be 1013 /// generated. Must be OMPD_barrier for explicit barrier generation. 1014 /// \param EmitChecks true if need to emit checks for cancellation barriers. 1015 /// \param ForceSimpleCall true simple barrier call must be emitted, false if 1016 /// runtime class decides which one to emit (simple or with cancellation 1017 /// checks). 1018 /// 1019 virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 1020 OpenMPDirectiveKind Kind, 1021 bool EmitChecks = true, 1022 bool ForceSimpleCall = false); 1023 1024 /// Check if the specified \a ScheduleKind is static non-chunked. 1025 /// This kind of worksharing directive is emitted without outer loop. 1026 /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. 1027 /// \param Chunked True if chunk is specified in the clause. 1028 /// 1029 virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, 1030 bool Chunked) const; 1031 1032 /// Check if the specified \a ScheduleKind is static non-chunked. 1033 /// This kind of distribute directive is emitted without outer loop. 1034 /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. 1035 /// \param Chunked True if chunk is specified in the clause. 1036 /// 1037 virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind, 1038 bool Chunked) const; 1039 1040 /// Check if the specified \a ScheduleKind is static chunked. 1041 /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. 1042 /// \param Chunked True if chunk is specified in the clause. 1043 /// 1044 virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, 1045 bool Chunked) const; 1046 1047 /// Check if the specified \a ScheduleKind is static non-chunked. 1048 /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. 1049 /// \param Chunked True if chunk is specified in the clause. 1050 /// 1051 virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind, 1052 bool Chunked) const; 1053 1054 /// Check if the specified \a ScheduleKind is dynamic. 1055 /// This kind of worksharing directive is emitted without outer loop. 1056 /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause. 1057 /// 1058 virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const; 1059 1060 /// struct with the values to be passed to the dispatch runtime function 1061 struct DispatchRTInput { 1062 /// Loop lower bound 1063 llvm::Value *LB = nullptr; 1064 /// Loop upper bound 1065 llvm::Value *UB = nullptr; 1066 /// Chunk size specified using 'schedule' clause (nullptr if chunk 1067 /// was not specified) 1068 llvm::Value *Chunk = nullptr; 1069 DispatchRTInput() = default; 1070 DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk) 1071 : LB(LB), UB(UB), Chunk(Chunk) {} 1072 }; 1073 1074 /// Call the appropriate runtime routine to initialize it before start 1075 /// of loop. 1076 1077 /// This is used for non static scheduled types and when the ordered 1078 /// clause is present on the loop construct. 1079 /// Depending on the loop schedule, it is necessary to call some runtime 1080 /// routine before start of the OpenMP loop to get the loop upper / lower 1081 /// bounds \a LB and \a UB and stride \a ST. 1082 /// 1083 /// \param CGF Reference to current CodeGenFunction. 1084 /// \param Loc Clang source location. 1085 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1086 /// \param IVSize Size of the iteration variable in bits. 1087 /// \param IVSigned Sign of the iteration variable. 1088 /// \param Ordered true if loop is ordered, false otherwise. 1089 /// \param DispatchValues struct containing llvm values for lower bound, upper 1090 /// bound, and chunk expression. 1091 /// For the default (nullptr) value, the chunk 1 will be used. 1092 /// 1093 virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, 1094 const OpenMPScheduleTy &ScheduleKind, 1095 unsigned IVSize, bool IVSigned, bool Ordered, 1096 const DispatchRTInput &DispatchValues); 1097 1098 /// Struct with the values to be passed to the static runtime function 1099 struct StaticRTInput { 1100 /// Size of the iteration variable in bits. 1101 unsigned IVSize = 0; 1102 /// Sign of the iteration variable. 1103 bool IVSigned = false; 1104 /// true if loop is ordered, false otherwise. 1105 bool Ordered = false; 1106 /// Address of the output variable in which the flag of the last iteration 1107 /// is returned. 1108 Address IL = Address::invalid(); 1109 /// Address of the output variable in which the lower iteration number is 1110 /// returned. 1111 Address LB = Address::invalid(); 1112 /// Address of the output variable in which the upper iteration number is 1113 /// returned. 1114 Address UB = Address::invalid(); 1115 /// Address of the output variable in which the stride value is returned 1116 /// necessary to generated the static_chunked scheduled loop. 1117 Address ST = Address::invalid(); 1118 /// Value of the chunk for the static_chunked scheduled loop. For the 1119 /// default (nullptr) value, the chunk 1 will be used. 1120 llvm::Value *Chunk = nullptr; 1121 StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL, 1122 Address LB, Address UB, Address ST, 1123 llvm::Value *Chunk = nullptr) 1124 : IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB), 1125 UB(UB), ST(ST), Chunk(Chunk) {} 1126 }; 1127 /// Call the appropriate runtime routine to initialize it before start 1128 /// of loop. 1129 /// 1130 /// This is used only in case of static schedule, when the user did not 1131 /// specify a ordered clause on the loop construct. 1132 /// Depending on the loop schedule, it is necessary to call some runtime 1133 /// routine before start of the OpenMP loop to get the loop upper / lower 1134 /// bounds LB and UB and stride ST. 1135 /// 1136 /// \param CGF Reference to current CodeGenFunction. 1137 /// \param Loc Clang source location. 1138 /// \param DKind Kind of the directive. 1139 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1140 /// \param Values Input arguments for the construct. 1141 /// 1142 virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 1143 OpenMPDirectiveKind DKind, 1144 const OpenMPScheduleTy &ScheduleKind, 1145 const StaticRTInput &Values); 1146 1147 /// 1148 /// \param CGF Reference to current CodeGenFunction. 1149 /// \param Loc Clang source location. 1150 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. 1151 /// \param Values Input arguments for the construct. 1152 /// 1153 virtual void emitDistributeStaticInit(CodeGenFunction &CGF, 1154 SourceLocation Loc, 1155 OpenMPDistScheduleClauseKind SchedKind, 1156 const StaticRTInput &Values); 1157 1158 /// Call the appropriate runtime routine to notify that we finished 1159 /// iteration of the ordered loop with the dynamic scheduling. 1160 /// 1161 /// \param CGF Reference to current CodeGenFunction. 1162 /// \param Loc Clang source location. 1163 /// \param IVSize Size of the iteration variable in bits. 1164 /// \param IVSigned Sign of the iteration variable. 1165 /// 1166 virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, 1167 SourceLocation Loc, unsigned IVSize, 1168 bool IVSigned); 1169 1170 /// Call the appropriate runtime routine to notify that we finished 1171 /// all the work with current loop. 1172 /// 1173 /// \param CGF Reference to current CodeGenFunction. 1174 /// \param Loc Clang source location. 1175 /// \param DKind Kind of the directive for which the static finish is emitted. 1176 /// 1177 virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, 1178 OpenMPDirectiveKind DKind); 1179 1180 /// Call __kmpc_dispatch_next( 1181 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 1182 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 1183 /// kmp_int[32|64] *p_stride); 1184 /// \param IVSize Size of the iteration variable in bits. 1185 /// \param IVSigned Sign of the iteration variable. 1186 /// \param IL Address of the output variable in which the flag of the 1187 /// last iteration is returned. 1188 /// \param LB Address of the output variable in which the lower iteration 1189 /// number is returned. 1190 /// \param UB Address of the output variable in which the upper iteration 1191 /// number is returned. 1192 /// \param ST Address of the output variable in which the stride value is 1193 /// returned. 1194 virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, 1195 unsigned IVSize, bool IVSigned, 1196 Address IL, Address LB, 1197 Address UB, Address ST); 1198 1199 /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 1200 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' 1201 /// clause. 1202 /// \param NumThreads An integer value of threads. 1203 virtual void emitNumThreadsClause(CodeGenFunction &CGF, 1204 llvm::Value *NumThreads, 1205 SourceLocation Loc); 1206 1207 /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 1208 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. 1209 virtual void emitProcBindClause(CodeGenFunction &CGF, 1210 llvm::omp::ProcBindKind ProcBind, 1211 SourceLocation Loc); 1212 1213 /// Returns address of the threadprivate variable for the current 1214 /// thread. 1215 /// \param VD Threadprivate variable. 1216 /// \param VDAddr Address of the global variable \a VD. 1217 /// \param Loc Location of the reference to threadprivate var. 1218 /// \return Address of the threadprivate variable for the current thread. 1219 virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, 1220 const VarDecl *VD, 1221 Address VDAddr, 1222 SourceLocation Loc); 1223 1224 /// Returns the address of the variable marked as declare target with link 1225 /// clause OR as declare target with to clause and unified memory. 1226 virtual Address getAddrOfDeclareTargetVar(const VarDecl *VD); 1227 1228 /// Emit a code for initialization of threadprivate variable. It emits 1229 /// a call to runtime library which adds initial value to the newly created 1230 /// threadprivate variable (if it is not constant) and registers destructor 1231 /// for the variable (if any). 1232 /// \param VD Threadprivate variable. 1233 /// \param VDAddr Address of the global variable \a VD. 1234 /// \param Loc Location of threadprivate declaration. 1235 /// \param PerformInit true if initialization expression is not constant. 1236 virtual llvm::Function * 1237 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, 1238 SourceLocation Loc, bool PerformInit, 1239 CodeGenFunction *CGF = nullptr); 1240 1241 /// Emit a code for initialization of declare target variable. 1242 /// \param VD Declare target variable. 1243 /// \param Addr Address of the global variable \a VD. 1244 /// \param PerformInit true if initialization expression is not constant. 1245 virtual bool emitDeclareTargetVarDefinition(const VarDecl *VD, 1246 llvm::GlobalVariable *Addr, 1247 bool PerformInit); 1248 1249 /// Creates artificial threadprivate variable with name \p Name and type \p 1250 /// VarType. 1251 /// \param VarType Type of the artificial threadprivate variable. 1252 /// \param Name Name of the artificial threadprivate variable. 1253 virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 1254 QualType VarType, 1255 StringRef Name); 1256 1257 /// Emit flush of the variables specified in 'omp flush' directive. 1258 /// \param Vars List of variables to flush. 1259 virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, 1260 SourceLocation Loc, llvm::AtomicOrdering AO); 1261 1262 /// Emit task region for the task directive. The task region is 1263 /// emitted in several steps: 1264 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 1265 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1266 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 1267 /// function: 1268 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 1269 /// TaskFunction(gtid, tt->part_id, tt->shareds); 1270 /// return 0; 1271 /// } 1272 /// 2. Copy a list of shared variables to field shareds of the resulting 1273 /// structure kmp_task_t returned by the previous call (if any). 1274 /// 3. Copy a pointer to destructions function to field destructions of the 1275 /// resulting structure kmp_task_t. 1276 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, 1277 /// kmp_task_t *new_task), where new_task is a resulting structure from 1278 /// previous items. 1279 /// \param D Current task directive. 1280 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 1281 /// /*part_id*/, captured_struct */*__context*/); 1282 /// \param SharedsTy A type which contains references the shared variables. 1283 /// \param Shareds Context with the list of shared variables from the \p 1284 /// TaskFunction. 1285 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 1286 /// otherwise. 1287 /// \param Data Additional data for task generation like tiednsee, final 1288 /// state, list of privates etc. 1289 virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 1290 const OMPExecutableDirective &D, 1291 llvm::Function *TaskFunction, QualType SharedsTy, 1292 Address Shareds, const Expr *IfCond, 1293 const OMPTaskDataTy &Data); 1294 1295 /// Emit task region for the taskloop directive. The taskloop region is 1296 /// emitted in several steps: 1297 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 1298 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1299 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 1300 /// function: 1301 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 1302 /// TaskFunction(gtid, tt->part_id, tt->shareds); 1303 /// return 0; 1304 /// } 1305 /// 2. Copy a list of shared variables to field shareds of the resulting 1306 /// structure kmp_task_t returned by the previous call (if any). 1307 /// 3. Copy a pointer to destructions function to field destructions of the 1308 /// resulting structure kmp_task_t. 1309 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t 1310 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int 1311 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task 1312 /// is a resulting structure from 1313 /// previous items. 1314 /// \param D Current task directive. 1315 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 1316 /// /*part_id*/, captured_struct */*__context*/); 1317 /// \param SharedsTy A type which contains references the shared variables. 1318 /// \param Shareds Context with the list of shared variables from the \p 1319 /// TaskFunction. 1320 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 1321 /// otherwise. 1322 /// \param Data Additional data for task generation like tiednsee, final 1323 /// state, list of privates etc. 1324 virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, 1325 const OMPLoopDirective &D, 1326 llvm::Function *TaskFunction, 1327 QualType SharedsTy, Address Shareds, 1328 const Expr *IfCond, const OMPTaskDataTy &Data); 1329 1330 /// Emit code for the directive that does not require outlining. 1331 /// 1332 /// \param InnermostKind Kind of innermost directive (for simple directives it 1333 /// is a directive itself, for combined - its innermost directive). 1334 /// \param CodeGen Code generation sequence for the \a D directive. 1335 /// \param HasCancel true if region has inner cancel directive, false 1336 /// otherwise. 1337 virtual void emitInlinedDirective(CodeGenFunction &CGF, 1338 OpenMPDirectiveKind InnermostKind, 1339 const RegionCodeGenTy &CodeGen, 1340 bool HasCancel = false); 1341 1342 /// Emits reduction function. 1343 /// \param ArgsType Array type containing pointers to reduction variables. 1344 /// \param Privates List of private copies for original reduction arguments. 1345 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 1346 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 1347 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 1348 /// or 'operator binop(LHS, RHS)'. 1349 llvm::Function *emitReductionFunction(SourceLocation Loc, 1350 llvm::Type *ArgsType, 1351 ArrayRef<const Expr *> Privates, 1352 ArrayRef<const Expr *> LHSExprs, 1353 ArrayRef<const Expr *> RHSExprs, 1354 ArrayRef<const Expr *> ReductionOps); 1355 1356 /// Emits single reduction combiner 1357 void emitSingleReductionCombiner(CodeGenFunction &CGF, 1358 const Expr *ReductionOp, 1359 const Expr *PrivateRef, 1360 const DeclRefExpr *LHS, 1361 const DeclRefExpr *RHS); 1362 1363 struct ReductionOptionsTy { 1364 bool WithNowait; 1365 bool SimpleReduction; 1366 OpenMPDirectiveKind ReductionKind; 1367 }; 1368 /// Emit a code for reduction clause. Next code should be emitted for 1369 /// reduction: 1370 /// \code 1371 /// 1372 /// static kmp_critical_name lock = { 0 }; 1373 /// 1374 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 1375 /// ... 1376 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 1377 /// ... 1378 /// } 1379 /// 1380 /// ... 1381 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 1382 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 1383 /// RedList, reduce_func, &<lock>)) { 1384 /// case 1: 1385 /// ... 1386 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 1387 /// ... 1388 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 1389 /// break; 1390 /// case 2: 1391 /// ... 1392 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 1393 /// ... 1394 /// break; 1395 /// default:; 1396 /// } 1397 /// \endcode 1398 /// 1399 /// \param Privates List of private copies for original reduction arguments. 1400 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 1401 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 1402 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 1403 /// or 'operator binop(LHS, RHS)'. 1404 /// \param Options List of options for reduction codegen: 1405 /// WithNowait true if parent directive has also nowait clause, false 1406 /// otherwise. 1407 /// SimpleReduction Emit reduction operation only. Used for omp simd 1408 /// directive on the host. 1409 /// ReductionKind The kind of reduction to perform. 1410 virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 1411 ArrayRef<const Expr *> Privates, 1412 ArrayRef<const Expr *> LHSExprs, 1413 ArrayRef<const Expr *> RHSExprs, 1414 ArrayRef<const Expr *> ReductionOps, 1415 ReductionOptionsTy Options); 1416 1417 /// Emit a code for initialization of task reduction clause. Next code 1418 /// should be emitted for reduction: 1419 /// \code 1420 /// 1421 /// _task_red_item_t red_data[n]; 1422 /// ... 1423 /// red_data[i].shar = &origs[i]; 1424 /// red_data[i].size = sizeof(origs[i]); 1425 /// red_data[i].f_init = (void*)RedInit<i>; 1426 /// red_data[i].f_fini = (void*)RedDest<i>; 1427 /// red_data[i].f_comb = (void*)RedOp<i>; 1428 /// red_data[i].flags = <Flag_i>; 1429 /// ... 1430 /// void* tg1 = __kmpc_task_reduction_init(gtid, n, red_data); 1431 /// \endcode 1432 /// 1433 /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. 1434 /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. 1435 /// \param Data Additional data for task generation like tiedness, final 1436 /// state, list of privates, reductions etc. 1437 virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, 1438 SourceLocation Loc, 1439 ArrayRef<const Expr *> LHSExprs, 1440 ArrayRef<const Expr *> RHSExprs, 1441 const OMPTaskDataTy &Data); 1442 1443 /// Required to resolve existing problems in the runtime. Emits threadprivate 1444 /// variables to store the size of the VLAs/array sections for 1445 /// initializer/combiner/finalizer functions. 1446 /// \param RCG Allows to reuse an existing data for the reductions. 1447 /// \param N Reduction item for which fixups must be emitted. 1448 virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, 1449 ReductionCodeGen &RCG, unsigned N); 1450 1451 /// Get the address of `void *` type of the privatue copy of the reduction 1452 /// item specified by the \p SharedLVal. 1453 /// \param ReductionsPtr Pointer to the reduction data returned by the 1454 /// emitTaskReductionInit function. 1455 /// \param SharedLVal Address of the original reduction item. 1456 virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, 1457 llvm::Value *ReductionsPtr, 1458 LValue SharedLVal); 1459 1460 /// Emit code for 'taskwait' directive. 1461 virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc); 1462 1463 /// Emit code for 'cancellation point' construct. 1464 /// \param CancelRegion Region kind for which the cancellation point must be 1465 /// emitted. 1466 /// 1467 virtual void emitCancellationPointCall(CodeGenFunction &CGF, 1468 SourceLocation Loc, 1469 OpenMPDirectiveKind CancelRegion); 1470 1471 /// Emit code for 'cancel' construct. 1472 /// \param IfCond Condition in the associated 'if' clause, if it was 1473 /// specified, nullptr otherwise. 1474 /// \param CancelRegion Region kind for which the cancel must be emitted. 1475 /// 1476 virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 1477 const Expr *IfCond, 1478 OpenMPDirectiveKind CancelRegion); 1479 1480 /// Emit outilined function for 'target' directive. 1481 /// \param D Directive to emit. 1482 /// \param ParentName Name of the function that encloses the target region. 1483 /// \param OutlinedFn Outlined function value to be defined by this call. 1484 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 1485 /// \param IsOffloadEntry True if the outlined function is an offload entry. 1486 /// \param CodeGen Code generation sequence for the \a D directive. 1487 /// An outlined function may not be an entry if, e.g. the if clause always 1488 /// evaluates to false. 1489 virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, 1490 StringRef ParentName, 1491 llvm::Function *&OutlinedFn, 1492 llvm::Constant *&OutlinedFnID, 1493 bool IsOffloadEntry, 1494 const RegionCodeGenTy &CodeGen); 1495 1496 /// Emit the target offloading code associated with \a D. The emitted 1497 /// code attempts offloading the execution to the device, an the event of 1498 /// a failure it executes the host version outlined in \a OutlinedFn. 1499 /// \param D Directive to emit. 1500 /// \param OutlinedFn Host version of the code to be offloaded. 1501 /// \param OutlinedFnID ID of host version of the code to be offloaded. 1502 /// \param IfCond Expression evaluated in if clause associated with the target 1503 /// directive, or null if no if clause is used. 1504 /// \param Device Expression evaluated in device clause associated with the 1505 /// target directive, or null if no device clause is used and device modifier. 1506 /// \param SizeEmitter Callback to emit number of iterations for loop-based 1507 /// directives. 1508 virtual void emitTargetCall( 1509 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1510 llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, 1511 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, 1512 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, 1513 const OMPLoopDirective &D)> 1514 SizeEmitter); 1515 1516 /// Emit the target regions enclosed in \a GD function definition or 1517 /// the function itself in case it is a valid device function. Returns true if 1518 /// \a GD was dealt with successfully. 1519 /// \param GD Function to scan. 1520 virtual bool emitTargetFunctions(GlobalDecl GD); 1521 1522 /// Emit the global variable if it is a valid device global variable. 1523 /// Returns true if \a GD was dealt with successfully. 1524 /// \param GD Variable declaration to emit. 1525 virtual bool emitTargetGlobalVariable(GlobalDecl GD); 1526 1527 /// Checks if the provided global decl \a GD is a declare target variable and 1528 /// registers it when emitting code for the host. 1529 virtual void registerTargetGlobalVariable(const VarDecl *VD, 1530 llvm::Constant *Addr); 1531 1532 /// Registers provided target firstprivate variable as global on the 1533 /// target. 1534 llvm::Constant *registerTargetFirstprivateCopy(CodeGenFunction &CGF, 1535 const VarDecl *VD); 1536 1537 /// Emit the global \a GD if it is meaningful for the target. Returns 1538 /// if it was emitted successfully. 1539 /// \param GD Global to scan. 1540 virtual bool emitTargetGlobal(GlobalDecl GD); 1541 1542 /// Creates and returns a registration function for when at least one 1543 /// requires directives was used in the current module. 1544 llvm::Function *emitRequiresDirectiveRegFun(); 1545 1546 /// Creates all the offload entries in the current compilation unit 1547 /// along with the associated metadata. 1548 void createOffloadEntriesAndInfoMetadata(); 1549 1550 /// Emits code for teams call of the \a OutlinedFn with 1551 /// variables captured in a record which address is stored in \a 1552 /// CapturedStruct. 1553 /// \param OutlinedFn Outlined function to be run by team masters. Type of 1554 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 1555 /// \param CapturedVars A pointer to the record with the references to 1556 /// variables used in \a OutlinedFn function. 1557 /// 1558 virtual void emitTeamsCall(CodeGenFunction &CGF, 1559 const OMPExecutableDirective &D, 1560 SourceLocation Loc, llvm::Function *OutlinedFn, 1561 ArrayRef<llvm::Value *> CapturedVars); 1562 1563 /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 1564 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code 1565 /// for num_teams clause. 1566 /// \param NumTeams An integer expression of teams. 1567 /// \param ThreadLimit An integer expression of threads. 1568 virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, 1569 const Expr *ThreadLimit, SourceLocation Loc); 1570 1571 /// Struct that keeps all the relevant information that should be kept 1572 /// throughout a 'target data' region. 1573 class TargetDataInfo { 1574 /// Set to true if device pointer information have to be obtained. 1575 bool RequiresDevicePointerInfo = false; 1576 1577 public: 1578 /// The array of base pointer passed to the runtime library. 1579 llvm::Value *BasePointersArray = nullptr; 1580 /// The array of section pointers passed to the runtime library. 1581 llvm::Value *PointersArray = nullptr; 1582 /// The array of sizes passed to the runtime library. 1583 llvm::Value *SizesArray = nullptr; 1584 /// The array of map types passed to the runtime library. 1585 llvm::Value *MapTypesArray = nullptr; 1586 /// The total number of pointers passed to the runtime library. 1587 unsigned NumberOfPtrs = 0u; 1588 /// Map between the a declaration of a capture and the corresponding base 1589 /// pointer address where the runtime returns the device pointers. 1590 llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap; 1591 1592 explicit TargetDataInfo() {} 1593 explicit TargetDataInfo(bool RequiresDevicePointerInfo) 1594 : RequiresDevicePointerInfo(RequiresDevicePointerInfo) {} 1595 /// Clear information about the data arrays. 1596 void clearArrayInfo() { 1597 BasePointersArray = nullptr; 1598 PointersArray = nullptr; 1599 SizesArray = nullptr; 1600 MapTypesArray = nullptr; 1601 NumberOfPtrs = 0u; 1602 } 1603 /// Return true if the current target data information has valid arrays. 1604 bool isValid() { 1605 return BasePointersArray && PointersArray && SizesArray && 1606 MapTypesArray && NumberOfPtrs; 1607 } 1608 bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; } 1609 }; 1610 1611 /// Emit the target data mapping code associated with \a D. 1612 /// \param D Directive to emit. 1613 /// \param IfCond Expression evaluated in if clause associated with the 1614 /// target directive, or null if no device clause is used. 1615 /// \param Device Expression evaluated in device clause associated with the 1616 /// target directive, or null if no device clause is used. 1617 /// \param Info A record used to store information that needs to be preserved 1618 /// until the region is closed. 1619 virtual void emitTargetDataCalls(CodeGenFunction &CGF, 1620 const OMPExecutableDirective &D, 1621 const Expr *IfCond, const Expr *Device, 1622 const RegionCodeGenTy &CodeGen, 1623 TargetDataInfo &Info); 1624 1625 /// Emit the data mapping/movement code associated with the directive 1626 /// \a D that should be of the form 'target [{enter|exit} data | update]'. 1627 /// \param D Directive to emit. 1628 /// \param IfCond Expression evaluated in if clause associated with the target 1629 /// directive, or null if no if clause is used. 1630 /// \param Device Expression evaluated in device clause associated with the 1631 /// target directive, or null if no device clause is used. 1632 virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF, 1633 const OMPExecutableDirective &D, 1634 const Expr *IfCond, 1635 const Expr *Device); 1636 1637 /// Marks function \a Fn with properly mangled versions of vector functions. 1638 /// \param FD Function marked as 'declare simd'. 1639 /// \param Fn LLVM function that must be marked with 'declare simd' 1640 /// attributes. 1641 virtual void emitDeclareSimdFunction(const FunctionDecl *FD, 1642 llvm::Function *Fn); 1643 1644 /// Emit initialization for doacross loop nesting support. 1645 /// \param D Loop-based construct used in doacross nesting construct. 1646 virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, 1647 ArrayRef<Expr *> NumIterations); 1648 1649 /// Emit code for doacross ordered directive with 'depend' clause. 1650 /// \param C 'depend' clause with 'sink|source' dependency kind. 1651 virtual void emitDoacrossOrdered(CodeGenFunction &CGF, 1652 const OMPDependClause *C); 1653 1654 /// Translates the native parameter of outlined function if this is required 1655 /// for target. 1656 /// \param FD Field decl from captured record for the parameter. 1657 /// \param NativeParam Parameter itself. 1658 virtual const VarDecl *translateParameter(const FieldDecl *FD, 1659 const VarDecl *NativeParam) const { 1660 return NativeParam; 1661 } 1662 1663 /// Gets the address of the native argument basing on the address of the 1664 /// target-specific parameter. 1665 /// \param NativeParam Parameter itself. 1666 /// \param TargetParam Corresponding target-specific parameter. 1667 virtual Address getParameterAddress(CodeGenFunction &CGF, 1668 const VarDecl *NativeParam, 1669 const VarDecl *TargetParam) const; 1670 1671 /// Choose default schedule type and chunk value for the 1672 /// dist_schedule clause. 1673 virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, 1674 const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, 1675 llvm::Value *&Chunk) const {} 1676 1677 /// Choose default schedule type and chunk value for the 1678 /// schedule clause. 1679 virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF, 1680 const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, 1681 const Expr *&ChunkExpr) const; 1682 1683 /// Emits call of the outlined function with the provided arguments, 1684 /// translating these arguments to correct target-specific arguments. 1685 virtual void 1686 emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, 1687 llvm::FunctionCallee OutlinedFn, 1688 ArrayRef<llvm::Value *> Args = llvm::None) const; 1689 1690 /// Emits OpenMP-specific function prolog. 1691 /// Required for device constructs. 1692 virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D); 1693 1694 /// Gets the OpenMP-specific address of the local variable. 1695 virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF, 1696 const VarDecl *VD); 1697 1698 /// Marks the declaration as already emitted for the device code and returns 1699 /// true, if it was marked already, and false, otherwise. 1700 bool markAsGlobalTarget(GlobalDecl GD); 1701 1702 /// Emit deferred declare target variables marked for deferred emission. 1703 void emitDeferredTargetDecls() const; 1704 1705 /// Adjust some parameters for the target-based directives, like addresses of 1706 /// the variables captured by reference in lambdas. 1707 virtual void 1708 adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, 1709 const OMPExecutableDirective &D) const; 1710 1711 /// Perform check on requires decl to ensure that target architecture 1712 /// supports unified addressing 1713 virtual void processRequiresDirective(const OMPRequiresDecl *D); 1714 1715 /// Gets default memory ordering as specified in requires directive. 1716 llvm::AtomicOrdering getDefaultMemoryOrdering() const; 1717 1718 /// Checks if the variable has associated OMPAllocateDeclAttr attribute with 1719 /// the predefined allocator and translates it into the corresponding address 1720 /// space. 1721 virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS); 1722 1723 /// Return whether the unified_shared_memory has been specified. 1724 bool hasRequiresUnifiedSharedMemory() const; 1725 1726 /// Checks if the \p VD variable is marked as nontemporal declaration in 1727 /// current context. 1728 bool isNontemporalDecl(const ValueDecl *VD) const; 1729 1730 /// Create specialized alloca to handle lastprivate conditionals. 1731 Address emitLastprivateConditionalInit(CodeGenFunction &CGF, 1732 const VarDecl *VD); 1733 1734 /// Checks if the provided \p LVal is lastprivate conditional and emits the 1735 /// code to update the value of the original variable. 1736 /// \code 1737 /// lastprivate(conditional: a) 1738 /// ... 1739 /// <type> a; 1740 /// lp_a = ...; 1741 /// #pragma omp critical(a) 1742 /// if (last_iv_a <= iv) { 1743 /// last_iv_a = iv; 1744 /// global_a = lp_a; 1745 /// } 1746 /// \endcode 1747 virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, 1748 const Expr *LHS); 1749 1750 /// Checks if the lastprivate conditional was updated in inner region and 1751 /// writes the value. 1752 /// \code 1753 /// lastprivate(conditional: a) 1754 /// ... 1755 /// <type> a;bool Fired = false; 1756 /// #pragma omp ... shared(a) 1757 /// { 1758 /// lp_a = ...; 1759 /// Fired = true; 1760 /// } 1761 /// if (Fired) { 1762 /// #pragma omp critical(a) 1763 /// if (last_iv_a <= iv) { 1764 /// last_iv_a = iv; 1765 /// global_a = lp_a; 1766 /// } 1767 /// Fired = false; 1768 /// } 1769 /// \endcode 1770 virtual void checkAndEmitSharedLastprivateConditional( 1771 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1772 const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls); 1773 1774 /// Gets the address of the global copy used for lastprivate conditional 1775 /// update, if any. 1776 /// \param PrivLVal LValue for the private copy. 1777 /// \param VD Original lastprivate declaration. 1778 virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF, 1779 LValue PrivLVal, 1780 const VarDecl *VD, 1781 SourceLocation Loc); 1782 1783 /// Emits list of dependecies based on the provided data (array of 1784 /// dependence/expression pairs). 1785 /// \returns Pointer to the first element of the array casted to VoidPtr type. 1786 std::pair<llvm::Value *, Address> 1787 emitDependClause(CodeGenFunction &CGF, 1788 ArrayRef<OMPTaskDataTy::DependData> Dependencies, 1789 SourceLocation Loc); 1790 1791 /// Emits list of dependecies based on the provided data (array of 1792 /// dependence/expression pairs) for depobj construct. In this case, the 1793 /// variable is allocated in dynamically. \returns Pointer to the first 1794 /// element of the array casted to VoidPtr type. 1795 Address emitDepobjDependClause(CodeGenFunction &CGF, 1796 const OMPTaskDataTy::DependData &Dependencies, 1797 SourceLocation Loc); 1798 1799 /// Emits the code to destroy the dependency object provided in depobj 1800 /// directive. 1801 void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, 1802 SourceLocation Loc); 1803 1804 /// Updates the dependency kind in the specified depobj object. 1805 /// \param DepobjLVal LValue for the main depobj object. 1806 /// \param NewDepKind New dependency kind. 1807 void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, 1808 OpenMPDependClauseKind NewDepKind, SourceLocation Loc); 1809 }; 1810 1811 /// Class supports emissionof SIMD-only code. 1812 class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime { 1813 public: 1814 explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {} 1815 ~CGOpenMPSIMDRuntime() override {} 1816 1817 /// Emits outlined function for the specified OpenMP parallel directive 1818 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 1819 /// kmp_int32 BoundID, struct context_vars*). 1820 /// \param D OpenMP directive. 1821 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1822 /// \param InnermostKind Kind of innermost directive (for simple directives it 1823 /// is a directive itself, for combined - its innermost directive). 1824 /// \param CodeGen Code generation sequence for the \a D directive. 1825 llvm::Function * 1826 emitParallelOutlinedFunction(const OMPExecutableDirective &D, 1827 const VarDecl *ThreadIDVar, 1828 OpenMPDirectiveKind InnermostKind, 1829 const RegionCodeGenTy &CodeGen) override; 1830 1831 /// Emits outlined function for the specified OpenMP teams directive 1832 /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, 1833 /// kmp_int32 BoundID, struct context_vars*). 1834 /// \param D OpenMP directive. 1835 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1836 /// \param InnermostKind Kind of innermost directive (for simple directives it 1837 /// is a directive itself, for combined - its innermost directive). 1838 /// \param CodeGen Code generation sequence for the \a D directive. 1839 llvm::Function * 1840 emitTeamsOutlinedFunction(const OMPExecutableDirective &D, 1841 const VarDecl *ThreadIDVar, 1842 OpenMPDirectiveKind InnermostKind, 1843 const RegionCodeGenTy &CodeGen) override; 1844 1845 /// Emits outlined function for the OpenMP task directive \a D. This 1846 /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* 1847 /// TaskT). 1848 /// \param D OpenMP directive. 1849 /// \param ThreadIDVar Variable for thread id in the current OpenMP region. 1850 /// \param PartIDVar Variable for partition id in the current OpenMP untied 1851 /// task region. 1852 /// \param TaskTVar Variable for task_t argument. 1853 /// \param InnermostKind Kind of innermost directive (for simple directives it 1854 /// is a directive itself, for combined - its innermost directive). 1855 /// \param CodeGen Code generation sequence for the \a D directive. 1856 /// \param Tied true if task is generated for tied task, false otherwise. 1857 /// \param NumberOfParts Number of parts in untied task. Ignored for tied 1858 /// tasks. 1859 /// 1860 llvm::Function *emitTaskOutlinedFunction( 1861 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1862 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 1863 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1864 bool Tied, unsigned &NumberOfParts) override; 1865 1866 /// Emits code for parallel or serial call of the \a OutlinedFn with 1867 /// variables captured in a record which address is stored in \a 1868 /// CapturedStruct. 1869 /// \param OutlinedFn Outlined function to be run in parallel threads. Type of 1870 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 1871 /// \param CapturedVars A pointer to the record with the references to 1872 /// variables used in \a OutlinedFn function. 1873 /// \param IfCond Condition in the associated 'if' clause, if it was 1874 /// specified, nullptr otherwise. 1875 /// 1876 void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 1877 llvm::Function *OutlinedFn, 1878 ArrayRef<llvm::Value *> CapturedVars, 1879 const Expr *IfCond) override; 1880 1881 /// Emits a critical region. 1882 /// \param CriticalName Name of the critical region. 1883 /// \param CriticalOpGen Generator for the statement associated with the given 1884 /// critical region. 1885 /// \param Hint Value of the 'hint' clause (optional). 1886 void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, 1887 const RegionCodeGenTy &CriticalOpGen, 1888 SourceLocation Loc, 1889 const Expr *Hint = nullptr) override; 1890 1891 /// Emits a master region. 1892 /// \param MasterOpGen Generator for the statement associated with the given 1893 /// master region. 1894 void emitMasterRegion(CodeGenFunction &CGF, 1895 const RegionCodeGenTy &MasterOpGen, 1896 SourceLocation Loc) override; 1897 1898 /// Emits code for a taskyield directive. 1899 void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override; 1900 1901 /// Emit a taskgroup region. 1902 /// \param TaskgroupOpGen Generator for the statement associated with the 1903 /// given taskgroup region. 1904 void emitTaskgroupRegion(CodeGenFunction &CGF, 1905 const RegionCodeGenTy &TaskgroupOpGen, 1906 SourceLocation Loc) override; 1907 1908 /// Emits a single region. 1909 /// \param SingleOpGen Generator for the statement associated with the given 1910 /// single region. 1911 void emitSingleRegion(CodeGenFunction &CGF, 1912 const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, 1913 ArrayRef<const Expr *> CopyprivateVars, 1914 ArrayRef<const Expr *> DestExprs, 1915 ArrayRef<const Expr *> SrcExprs, 1916 ArrayRef<const Expr *> AssignmentOps) override; 1917 1918 /// Emit an ordered region. 1919 /// \param OrderedOpGen Generator for the statement associated with the given 1920 /// ordered region. 1921 void emitOrderedRegion(CodeGenFunction &CGF, 1922 const RegionCodeGenTy &OrderedOpGen, 1923 SourceLocation Loc, bool IsThreads) override; 1924 1925 /// Emit an implicit/explicit barrier for OpenMP threads. 1926 /// \param Kind Directive for which this implicit barrier call must be 1927 /// generated. Must be OMPD_barrier for explicit barrier generation. 1928 /// \param EmitChecks true if need to emit checks for cancellation barriers. 1929 /// \param ForceSimpleCall true simple barrier call must be emitted, false if 1930 /// runtime class decides which one to emit (simple or with cancellation 1931 /// checks). 1932 /// 1933 void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 1934 OpenMPDirectiveKind Kind, bool EmitChecks = true, 1935 bool ForceSimpleCall = false) override; 1936 1937 /// This is used for non static scheduled types and when the ordered 1938 /// clause is present on the loop construct. 1939 /// Depending on the loop schedule, it is necessary to call some runtime 1940 /// routine before start of the OpenMP loop to get the loop upper / lower 1941 /// bounds \a LB and \a UB and stride \a ST. 1942 /// 1943 /// \param CGF Reference to current CodeGenFunction. 1944 /// \param Loc Clang source location. 1945 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1946 /// \param IVSize Size of the iteration variable in bits. 1947 /// \param IVSigned Sign of the iteration variable. 1948 /// \param Ordered true if loop is ordered, false otherwise. 1949 /// \param DispatchValues struct containing llvm values for lower bound, upper 1950 /// bound, and chunk expression. 1951 /// For the default (nullptr) value, the chunk 1 will be used. 1952 /// 1953 void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, 1954 const OpenMPScheduleTy &ScheduleKind, 1955 unsigned IVSize, bool IVSigned, bool Ordered, 1956 const DispatchRTInput &DispatchValues) override; 1957 1958 /// Call the appropriate runtime routine to initialize it before start 1959 /// of loop. 1960 /// 1961 /// This is used only in case of static schedule, when the user did not 1962 /// specify a ordered clause on the loop construct. 1963 /// Depending on the loop schedule, it is necessary to call some runtime 1964 /// routine before start of the OpenMP loop to get the loop upper / lower 1965 /// bounds LB and UB and stride ST. 1966 /// 1967 /// \param CGF Reference to current CodeGenFunction. 1968 /// \param Loc Clang source location. 1969 /// \param DKind Kind of the directive. 1970 /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. 1971 /// \param Values Input arguments for the construct. 1972 /// 1973 void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 1974 OpenMPDirectiveKind DKind, 1975 const OpenMPScheduleTy &ScheduleKind, 1976 const StaticRTInput &Values) override; 1977 1978 /// 1979 /// \param CGF Reference to current CodeGenFunction. 1980 /// \param Loc Clang source location. 1981 /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. 1982 /// \param Values Input arguments for the construct. 1983 /// 1984 void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, 1985 OpenMPDistScheduleClauseKind SchedKind, 1986 const StaticRTInput &Values) override; 1987 1988 /// Call the appropriate runtime routine to notify that we finished 1989 /// iteration of the ordered loop with the dynamic scheduling. 1990 /// 1991 /// \param CGF Reference to current CodeGenFunction. 1992 /// \param Loc Clang source location. 1993 /// \param IVSize Size of the iteration variable in bits. 1994 /// \param IVSigned Sign of the iteration variable. 1995 /// 1996 void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, 1997 unsigned IVSize, bool IVSigned) override; 1998 1999 /// Call the appropriate runtime routine to notify that we finished 2000 /// all the work with current loop. 2001 /// 2002 /// \param CGF Reference to current CodeGenFunction. 2003 /// \param Loc Clang source location. 2004 /// \param DKind Kind of the directive for which the static finish is emitted. 2005 /// 2006 void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, 2007 OpenMPDirectiveKind DKind) override; 2008 2009 /// Call __kmpc_dispatch_next( 2010 /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 2011 /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 2012 /// kmp_int[32|64] *p_stride); 2013 /// \param IVSize Size of the iteration variable in bits. 2014 /// \param IVSigned Sign of the iteration variable. 2015 /// \param IL Address of the output variable in which the flag of the 2016 /// last iteration is returned. 2017 /// \param LB Address of the output variable in which the lower iteration 2018 /// number is returned. 2019 /// \param UB Address of the output variable in which the upper iteration 2020 /// number is returned. 2021 /// \param ST Address of the output variable in which the stride value is 2022 /// returned. 2023 llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, 2024 unsigned IVSize, bool IVSigned, Address IL, 2025 Address LB, Address UB, Address ST) override; 2026 2027 /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 2028 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' 2029 /// clause. 2030 /// \param NumThreads An integer value of threads. 2031 void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, 2032 SourceLocation Loc) override; 2033 2034 /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 2035 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. 2036 void emitProcBindClause(CodeGenFunction &CGF, 2037 llvm::omp::ProcBindKind ProcBind, 2038 SourceLocation Loc) override; 2039 2040 /// Returns address of the threadprivate variable for the current 2041 /// thread. 2042 /// \param VD Threadprivate variable. 2043 /// \param VDAddr Address of the global variable \a VD. 2044 /// \param Loc Location of the reference to threadprivate var. 2045 /// \return Address of the threadprivate variable for the current thread. 2046 Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, 2047 Address VDAddr, SourceLocation Loc) override; 2048 2049 /// Emit a code for initialization of threadprivate variable. It emits 2050 /// a call to runtime library which adds initial value to the newly created 2051 /// threadprivate variable (if it is not constant) and registers destructor 2052 /// for the variable (if any). 2053 /// \param VD Threadprivate variable. 2054 /// \param VDAddr Address of the global variable \a VD. 2055 /// \param Loc Location of threadprivate declaration. 2056 /// \param PerformInit true if initialization expression is not constant. 2057 llvm::Function * 2058 emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, 2059 SourceLocation Loc, bool PerformInit, 2060 CodeGenFunction *CGF = nullptr) override; 2061 2062 /// Creates artificial threadprivate variable with name \p Name and type \p 2063 /// VarType. 2064 /// \param VarType Type of the artificial threadprivate variable. 2065 /// \param Name Name of the artificial threadprivate variable. 2066 Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 2067 QualType VarType, 2068 StringRef Name) override; 2069 2070 /// Emit flush of the variables specified in 'omp flush' directive. 2071 /// \param Vars List of variables to flush. 2072 void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, 2073 SourceLocation Loc, llvm::AtomicOrdering AO) override; 2074 2075 /// Emit task region for the task directive. The task region is 2076 /// emitted in several steps: 2077 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 2078 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 2079 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 2080 /// function: 2081 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 2082 /// TaskFunction(gtid, tt->part_id, tt->shareds); 2083 /// return 0; 2084 /// } 2085 /// 2. Copy a list of shared variables to field shareds of the resulting 2086 /// structure kmp_task_t returned by the previous call (if any). 2087 /// 3. Copy a pointer to destructions function to field destructions of the 2088 /// resulting structure kmp_task_t. 2089 /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, 2090 /// kmp_task_t *new_task), where new_task is a resulting structure from 2091 /// previous items. 2092 /// \param D Current task directive. 2093 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 2094 /// /*part_id*/, captured_struct */*__context*/); 2095 /// \param SharedsTy A type which contains references the shared variables. 2096 /// \param Shareds Context with the list of shared variables from the \p 2097 /// TaskFunction. 2098 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 2099 /// otherwise. 2100 /// \param Data Additional data for task generation like tiednsee, final 2101 /// state, list of privates etc. 2102 void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 2103 const OMPExecutableDirective &D, 2104 llvm::Function *TaskFunction, QualType SharedsTy, 2105 Address Shareds, const Expr *IfCond, 2106 const OMPTaskDataTy &Data) override; 2107 2108 /// Emit task region for the taskloop directive. The taskloop region is 2109 /// emitted in several steps: 2110 /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 2111 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 2112 /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the 2113 /// function: 2114 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 2115 /// TaskFunction(gtid, tt->part_id, tt->shareds); 2116 /// return 0; 2117 /// } 2118 /// 2. Copy a list of shared variables to field shareds of the resulting 2119 /// structure kmp_task_t returned by the previous call (if any). 2120 /// 3. Copy a pointer to destructions function to field destructions of the 2121 /// resulting structure kmp_task_t. 2122 /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t 2123 /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int 2124 /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task 2125 /// is a resulting structure from 2126 /// previous items. 2127 /// \param D Current task directive. 2128 /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 2129 /// /*part_id*/, captured_struct */*__context*/); 2130 /// \param SharedsTy A type which contains references the shared variables. 2131 /// \param Shareds Context with the list of shared variables from the \p 2132 /// TaskFunction. 2133 /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr 2134 /// otherwise. 2135 /// \param Data Additional data for task generation like tiednsee, final 2136 /// state, list of privates etc. 2137 void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, 2138 const OMPLoopDirective &D, llvm::Function *TaskFunction, 2139 QualType SharedsTy, Address Shareds, const Expr *IfCond, 2140 const OMPTaskDataTy &Data) override; 2141 2142 /// Emit a code for reduction clause. Next code should be emitted for 2143 /// reduction: 2144 /// \code 2145 /// 2146 /// static kmp_critical_name lock = { 0 }; 2147 /// 2148 /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 2149 /// ... 2150 /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 2151 /// ... 2152 /// } 2153 /// 2154 /// ... 2155 /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 2156 /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 2157 /// RedList, reduce_func, &<lock>)) { 2158 /// case 1: 2159 /// ... 2160 /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 2161 /// ... 2162 /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 2163 /// break; 2164 /// case 2: 2165 /// ... 2166 /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 2167 /// ... 2168 /// break; 2169 /// default:; 2170 /// } 2171 /// \endcode 2172 /// 2173 /// \param Privates List of private copies for original reduction arguments. 2174 /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. 2175 /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. 2176 /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' 2177 /// or 'operator binop(LHS, RHS)'. 2178 /// \param Options List of options for reduction codegen: 2179 /// WithNowait true if parent directive has also nowait clause, false 2180 /// otherwise. 2181 /// SimpleReduction Emit reduction operation only. Used for omp simd 2182 /// directive on the host. 2183 /// ReductionKind The kind of reduction to perform. 2184 void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 2185 ArrayRef<const Expr *> Privates, 2186 ArrayRef<const Expr *> LHSExprs, 2187 ArrayRef<const Expr *> RHSExprs, 2188 ArrayRef<const Expr *> ReductionOps, 2189 ReductionOptionsTy Options) override; 2190 2191 /// Emit a code for initialization of task reduction clause. Next code 2192 /// should be emitted for reduction: 2193 /// \code 2194 /// 2195 /// _task_red_item_t red_data[n]; 2196 /// ... 2197 /// red_data[i].shar = &origs[i]; 2198 /// red_data[i].size = sizeof(origs[i]); 2199 /// red_data[i].f_init = (void*)RedInit<i>; 2200 /// red_data[i].f_fini = (void*)RedDest<i>; 2201 /// red_data[i].f_comb = (void*)RedOp<i>; 2202 /// red_data[i].flags = <Flag_i>; 2203 /// ... 2204 /// void* tg1 = __kmpc_task_reduction_init(gtid, n, red_data); 2205 /// \endcode 2206 /// 2207 /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. 2208 /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. 2209 /// \param Data Additional data for task generation like tiedness, final 2210 /// state, list of privates, reductions etc. 2211 llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, 2212 ArrayRef<const Expr *> LHSExprs, 2213 ArrayRef<const Expr *> RHSExprs, 2214 const OMPTaskDataTy &Data) override; 2215 2216 /// Required to resolve existing problems in the runtime. Emits threadprivate 2217 /// variables to store the size of the VLAs/array sections for 2218 /// initializer/combiner/finalizer functions + emits threadprivate variable to 2219 /// store the pointer to the original reduction item for the custom 2220 /// initializer defined by declare reduction construct. 2221 /// \param RCG Allows to reuse an existing data for the reductions. 2222 /// \param N Reduction item for which fixups must be emitted. 2223 void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, 2224 ReductionCodeGen &RCG, unsigned N) override; 2225 2226 /// Get the address of `void *` type of the privatue copy of the reduction 2227 /// item specified by the \p SharedLVal. 2228 /// \param ReductionsPtr Pointer to the reduction data returned by the 2229 /// emitTaskReductionInit function. 2230 /// \param SharedLVal Address of the original reduction item. 2231 Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, 2232 llvm::Value *ReductionsPtr, 2233 LValue SharedLVal) override; 2234 2235 /// Emit code for 'taskwait' directive. 2236 void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc) override; 2237 2238 /// Emit code for 'cancellation point' construct. 2239 /// \param CancelRegion Region kind for which the cancellation point must be 2240 /// emitted. 2241 /// 2242 void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, 2243 OpenMPDirectiveKind CancelRegion) override; 2244 2245 /// Emit code for 'cancel' construct. 2246 /// \param IfCond Condition in the associated 'if' clause, if it was 2247 /// specified, nullptr otherwise. 2248 /// \param CancelRegion Region kind for which the cancel must be emitted. 2249 /// 2250 void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 2251 const Expr *IfCond, 2252 OpenMPDirectiveKind CancelRegion) override; 2253 2254 /// Emit outilined function for 'target' directive. 2255 /// \param D Directive to emit. 2256 /// \param ParentName Name of the function that encloses the target region. 2257 /// \param OutlinedFn Outlined function value to be defined by this call. 2258 /// \param OutlinedFnID Outlined function ID value to be defined by this call. 2259 /// \param IsOffloadEntry True if the outlined function is an offload entry. 2260 /// \param CodeGen Code generation sequence for the \a D directive. 2261 /// An outlined function may not be an entry if, e.g. the if clause always 2262 /// evaluates to false. 2263 void emitTargetOutlinedFunction(const OMPExecutableDirective &D, 2264 StringRef ParentName, 2265 llvm::Function *&OutlinedFn, 2266 llvm::Constant *&OutlinedFnID, 2267 bool IsOffloadEntry, 2268 const RegionCodeGenTy &CodeGen) override; 2269 2270 /// Emit the target offloading code associated with \a D. The emitted 2271 /// code attempts offloading the execution to the device, an the event of 2272 /// a failure it executes the host version outlined in \a OutlinedFn. 2273 /// \param D Directive to emit. 2274 /// \param OutlinedFn Host version of the code to be offloaded. 2275 /// \param OutlinedFnID ID of host version of the code to be offloaded. 2276 /// \param IfCond Expression evaluated in if clause associated with the target 2277 /// directive, or null if no if clause is used. 2278 /// \param Device Expression evaluated in device clause associated with the 2279 /// target directive, or null if no device clause is used and device modifier. 2280 void emitTargetCall( 2281 CodeGenFunction &CGF, const OMPExecutableDirective &D, 2282 llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, 2283 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, 2284 llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, 2285 const OMPLoopDirective &D)> 2286 SizeEmitter) override; 2287 2288 /// Emit the target regions enclosed in \a GD function definition or 2289 /// the function itself in case it is a valid device function. Returns true if 2290 /// \a GD was dealt with successfully. 2291 /// \param GD Function to scan. 2292 bool emitTargetFunctions(GlobalDecl GD) override; 2293 2294 /// Emit the global variable if it is a valid device global variable. 2295 /// Returns true if \a GD was dealt with successfully. 2296 /// \param GD Variable declaration to emit. 2297 bool emitTargetGlobalVariable(GlobalDecl GD) override; 2298 2299 /// Emit the global \a GD if it is meaningful for the target. Returns 2300 /// if it was emitted successfully. 2301 /// \param GD Global to scan. 2302 bool emitTargetGlobal(GlobalDecl GD) override; 2303 2304 /// Emits code for teams call of the \a OutlinedFn with 2305 /// variables captured in a record which address is stored in \a 2306 /// CapturedStruct. 2307 /// \param OutlinedFn Outlined function to be run by team masters. Type of 2308 /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). 2309 /// \param CapturedVars A pointer to the record with the references to 2310 /// variables used in \a OutlinedFn function. 2311 /// 2312 void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, 2313 SourceLocation Loc, llvm::Function *OutlinedFn, 2314 ArrayRef<llvm::Value *> CapturedVars) override; 2315 2316 /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 2317 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code 2318 /// for num_teams clause. 2319 /// \param NumTeams An integer expression of teams. 2320 /// \param ThreadLimit An integer expression of threads. 2321 void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, 2322 const Expr *ThreadLimit, SourceLocation Loc) override; 2323 2324 /// Emit the target data mapping code associated with \a D. 2325 /// \param D Directive to emit. 2326 /// \param IfCond Expression evaluated in if clause associated with the 2327 /// target directive, or null if no device clause is used. 2328 /// \param Device Expression evaluated in device clause associated with the 2329 /// target directive, or null if no device clause is used. 2330 /// \param Info A record used to store information that needs to be preserved 2331 /// until the region is closed. 2332 void emitTargetDataCalls(CodeGenFunction &CGF, 2333 const OMPExecutableDirective &D, const Expr *IfCond, 2334 const Expr *Device, const RegionCodeGenTy &CodeGen, 2335 TargetDataInfo &Info) override; 2336 2337 /// Emit the data mapping/movement code associated with the directive 2338 /// \a D that should be of the form 'target [{enter|exit} data | update]'. 2339 /// \param D Directive to emit. 2340 /// \param IfCond Expression evaluated in if clause associated with the target 2341 /// directive, or null if no if clause is used. 2342 /// \param Device Expression evaluated in device clause associated with the 2343 /// target directive, or null if no device clause is used. 2344 void emitTargetDataStandAloneCall(CodeGenFunction &CGF, 2345 const OMPExecutableDirective &D, 2346 const Expr *IfCond, 2347 const Expr *Device) override; 2348 2349 /// Emit initialization for doacross loop nesting support. 2350 /// \param D Loop-based construct used in doacross nesting construct. 2351 void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, 2352 ArrayRef<Expr *> NumIterations) override; 2353 2354 /// Emit code for doacross ordered directive with 'depend' clause. 2355 /// \param C 'depend' clause with 'sink|source' dependency kind. 2356 void emitDoacrossOrdered(CodeGenFunction &CGF, 2357 const OMPDependClause *C) override; 2358 2359 /// Translates the native parameter of outlined function if this is required 2360 /// for target. 2361 /// \param FD Field decl from captured record for the parameter. 2362 /// \param NativeParam Parameter itself. 2363 const VarDecl *translateParameter(const FieldDecl *FD, 2364 const VarDecl *NativeParam) const override; 2365 2366 /// Gets the address of the native argument basing on the address of the 2367 /// target-specific parameter. 2368 /// \param NativeParam Parameter itself. 2369 /// \param TargetParam Corresponding target-specific parameter. 2370 Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, 2371 const VarDecl *TargetParam) const override; 2372 2373 /// Gets the OpenMP-specific address of the local variable. 2374 Address getAddressOfLocalVariable(CodeGenFunction &CGF, 2375 const VarDecl *VD) override { 2376 return Address::invalid(); 2377 } 2378 }; 2379 2380 } // namespace CodeGen 2381 } // namespace clang 2382 2383 #endif 2384