1 //===----- CGOpenMPRuntime.cpp - Interface to OpenMP Runtimes -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This provides a class for OpenMP runtime code generation. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGCXXABI.h" 15 #include "CGCleanup.h" 16 #include "CGOpenMPRuntime.h" 17 #include "CGRecordLayout.h" 18 #include "CodeGenFunction.h" 19 #include "clang/CodeGen/ConstantInitBuilder.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/StmtOpenMP.h" 22 #include "clang/Basic/BitmaskEnum.h" 23 #include "llvm/ADT/ArrayRef.h" 24 #include "llvm/Bitcode/BitcodeReader.h" 25 #include "llvm/IR/CallSite.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/GlobalValue.h" 28 #include "llvm/IR/Value.h" 29 #include "llvm/Support/Format.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <cassert> 32 33 using namespace clang; 34 using namespace CodeGen; 35 36 namespace { 37 /// Base class for handling code generation inside OpenMP regions. 38 class CGOpenMPRegionInfo : public CodeGenFunction::CGCapturedStmtInfo { 39 public: 40 /// Kinds of OpenMP regions used in codegen. 41 enum CGOpenMPRegionKind { 42 /// Region with outlined function for standalone 'parallel' 43 /// directive. 44 ParallelOutlinedRegion, 45 /// Region with outlined function for standalone 'task' directive. 46 TaskOutlinedRegion, 47 /// Region for constructs that do not require function outlining, 48 /// like 'for', 'sections', 'atomic' etc. directives. 49 InlinedRegion, 50 /// Region with outlined function for standalone 'target' directive. 51 TargetRegion, 52 }; 53 54 CGOpenMPRegionInfo(const CapturedStmt &CS, 55 const CGOpenMPRegionKind RegionKind, 56 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, 57 bool HasCancel) 58 : CGCapturedStmtInfo(CS, CR_OpenMP), RegionKind(RegionKind), 59 CodeGen(CodeGen), Kind(Kind), HasCancel(HasCancel) {} 60 61 CGOpenMPRegionInfo(const CGOpenMPRegionKind RegionKind, 62 const RegionCodeGenTy &CodeGen, OpenMPDirectiveKind Kind, 63 bool HasCancel) 64 : CGCapturedStmtInfo(CR_OpenMP), RegionKind(RegionKind), CodeGen(CodeGen), 65 Kind(Kind), HasCancel(HasCancel) {} 66 67 /// Get a variable or parameter for storing global thread id 68 /// inside OpenMP construct. 69 virtual const VarDecl *getThreadIDVariable() const = 0; 70 71 /// Emit the captured statement body. 72 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override; 73 74 /// Get an LValue for the current ThreadID variable. 75 /// \return LValue for thread id variable. This LValue always has type int32*. 76 virtual LValue getThreadIDVariableLValue(CodeGenFunction &CGF); 77 78 virtual void emitUntiedSwitch(CodeGenFunction & /*CGF*/) {} 79 80 CGOpenMPRegionKind getRegionKind() const { return RegionKind; } 81 82 OpenMPDirectiveKind getDirectiveKind() const { return Kind; } 83 84 bool hasCancel() const { return HasCancel; } 85 86 static bool classof(const CGCapturedStmtInfo *Info) { 87 return Info->getKind() == CR_OpenMP; 88 } 89 90 ~CGOpenMPRegionInfo() override = default; 91 92 protected: 93 CGOpenMPRegionKind RegionKind; 94 RegionCodeGenTy CodeGen; 95 OpenMPDirectiveKind Kind; 96 bool HasCancel; 97 }; 98 99 /// API for captured statement code generation in OpenMP constructs. 100 class CGOpenMPOutlinedRegionInfo final : public CGOpenMPRegionInfo { 101 public: 102 CGOpenMPOutlinedRegionInfo(const CapturedStmt &CS, const VarDecl *ThreadIDVar, 103 const RegionCodeGenTy &CodeGen, 104 OpenMPDirectiveKind Kind, bool HasCancel, 105 StringRef HelperName) 106 : CGOpenMPRegionInfo(CS, ParallelOutlinedRegion, CodeGen, Kind, 107 HasCancel), 108 ThreadIDVar(ThreadIDVar), HelperName(HelperName) { 109 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region."); 110 } 111 112 /// Get a variable or parameter for storing global thread id 113 /// inside OpenMP construct. 114 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } 115 116 /// Get the name of the capture helper. 117 StringRef getHelperName() const override { return HelperName; } 118 119 static bool classof(const CGCapturedStmtInfo *Info) { 120 return CGOpenMPRegionInfo::classof(Info) && 121 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == 122 ParallelOutlinedRegion; 123 } 124 125 private: 126 /// A variable or parameter storing global thread id for OpenMP 127 /// constructs. 128 const VarDecl *ThreadIDVar; 129 StringRef HelperName; 130 }; 131 132 /// API for captured statement code generation in OpenMP constructs. 133 class CGOpenMPTaskOutlinedRegionInfo final : public CGOpenMPRegionInfo { 134 public: 135 class UntiedTaskActionTy final : public PrePostActionTy { 136 bool Untied; 137 const VarDecl *PartIDVar; 138 const RegionCodeGenTy UntiedCodeGen; 139 llvm::SwitchInst *UntiedSwitch = nullptr; 140 141 public: 142 UntiedTaskActionTy(bool Tied, const VarDecl *PartIDVar, 143 const RegionCodeGenTy &UntiedCodeGen) 144 : Untied(!Tied), PartIDVar(PartIDVar), UntiedCodeGen(UntiedCodeGen) {} 145 void Enter(CodeGenFunction &CGF) override { 146 if (Untied) { 147 // Emit task switching point. 148 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( 149 CGF.GetAddrOfLocalVar(PartIDVar), 150 PartIDVar->getType()->castAs<PointerType>()); 151 llvm::Value *Res = 152 CGF.EmitLoadOfScalar(PartIdLVal, PartIDVar->getLocation()); 153 llvm::BasicBlock *DoneBB = CGF.createBasicBlock(".untied.done."); 154 UntiedSwitch = CGF.Builder.CreateSwitch(Res, DoneBB); 155 CGF.EmitBlock(DoneBB); 156 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); 157 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); 158 UntiedSwitch->addCase(CGF.Builder.getInt32(0), 159 CGF.Builder.GetInsertBlock()); 160 emitUntiedSwitch(CGF); 161 } 162 } 163 void emitUntiedSwitch(CodeGenFunction &CGF) const { 164 if (Untied) { 165 LValue PartIdLVal = CGF.EmitLoadOfPointerLValue( 166 CGF.GetAddrOfLocalVar(PartIDVar), 167 PartIDVar->getType()->castAs<PointerType>()); 168 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), 169 PartIdLVal); 170 UntiedCodeGen(CGF); 171 CodeGenFunction::JumpDest CurPoint = 172 CGF.getJumpDestInCurrentScope(".untied.next."); 173 CGF.EmitBranchThroughCleanup(CGF.ReturnBlock); 174 CGF.EmitBlock(CGF.createBasicBlock(".untied.jmp.")); 175 UntiedSwitch->addCase(CGF.Builder.getInt32(UntiedSwitch->getNumCases()), 176 CGF.Builder.GetInsertBlock()); 177 CGF.EmitBranchThroughCleanup(CurPoint); 178 CGF.EmitBlock(CurPoint.getBlock()); 179 } 180 } 181 unsigned getNumberOfParts() const { return UntiedSwitch->getNumCases(); } 182 }; 183 CGOpenMPTaskOutlinedRegionInfo(const CapturedStmt &CS, 184 const VarDecl *ThreadIDVar, 185 const RegionCodeGenTy &CodeGen, 186 OpenMPDirectiveKind Kind, bool HasCancel, 187 const UntiedTaskActionTy &Action) 188 : CGOpenMPRegionInfo(CS, TaskOutlinedRegion, CodeGen, Kind, HasCancel), 189 ThreadIDVar(ThreadIDVar), Action(Action) { 190 assert(ThreadIDVar != nullptr && "No ThreadID in OpenMP region."); 191 } 192 193 /// Get a variable or parameter for storing global thread id 194 /// inside OpenMP construct. 195 const VarDecl *getThreadIDVariable() const override { return ThreadIDVar; } 196 197 /// Get an LValue for the current ThreadID variable. 198 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override; 199 200 /// Get the name of the capture helper. 201 StringRef getHelperName() const override { return ".omp_outlined."; } 202 203 void emitUntiedSwitch(CodeGenFunction &CGF) override { 204 Action.emitUntiedSwitch(CGF); 205 } 206 207 static bool classof(const CGCapturedStmtInfo *Info) { 208 return CGOpenMPRegionInfo::classof(Info) && 209 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == 210 TaskOutlinedRegion; 211 } 212 213 private: 214 /// A variable or parameter storing global thread id for OpenMP 215 /// constructs. 216 const VarDecl *ThreadIDVar; 217 /// Action for emitting code for untied tasks. 218 const UntiedTaskActionTy &Action; 219 }; 220 221 /// API for inlined captured statement code generation in OpenMP 222 /// constructs. 223 class CGOpenMPInlinedRegionInfo : public CGOpenMPRegionInfo { 224 public: 225 CGOpenMPInlinedRegionInfo(CodeGenFunction::CGCapturedStmtInfo *OldCSI, 226 const RegionCodeGenTy &CodeGen, 227 OpenMPDirectiveKind Kind, bool HasCancel) 228 : CGOpenMPRegionInfo(InlinedRegion, CodeGen, Kind, HasCancel), 229 OldCSI(OldCSI), 230 OuterRegionInfo(dyn_cast_or_null<CGOpenMPRegionInfo>(OldCSI)) {} 231 232 // Retrieve the value of the context parameter. 233 llvm::Value *getContextValue() const override { 234 if (OuterRegionInfo) 235 return OuterRegionInfo->getContextValue(); 236 llvm_unreachable("No context value for inlined OpenMP region"); 237 } 238 239 void setContextValue(llvm::Value *V) override { 240 if (OuterRegionInfo) { 241 OuterRegionInfo->setContextValue(V); 242 return; 243 } 244 llvm_unreachable("No context value for inlined OpenMP region"); 245 } 246 247 /// Lookup the captured field decl for a variable. 248 const FieldDecl *lookup(const VarDecl *VD) const override { 249 if (OuterRegionInfo) 250 return OuterRegionInfo->lookup(VD); 251 // If there is no outer outlined region,no need to lookup in a list of 252 // captured variables, we can use the original one. 253 return nullptr; 254 } 255 256 FieldDecl *getThisFieldDecl() const override { 257 if (OuterRegionInfo) 258 return OuterRegionInfo->getThisFieldDecl(); 259 return nullptr; 260 } 261 262 /// Get a variable or parameter for storing global thread id 263 /// inside OpenMP construct. 264 const VarDecl *getThreadIDVariable() const override { 265 if (OuterRegionInfo) 266 return OuterRegionInfo->getThreadIDVariable(); 267 return nullptr; 268 } 269 270 /// Get an LValue for the current ThreadID variable. 271 LValue getThreadIDVariableLValue(CodeGenFunction &CGF) override { 272 if (OuterRegionInfo) 273 return OuterRegionInfo->getThreadIDVariableLValue(CGF); 274 llvm_unreachable("No LValue for inlined OpenMP construct"); 275 } 276 277 /// Get the name of the capture helper. 278 StringRef getHelperName() const override { 279 if (auto *OuterRegionInfo = getOldCSI()) 280 return OuterRegionInfo->getHelperName(); 281 llvm_unreachable("No helper name for inlined OpenMP construct"); 282 } 283 284 void emitUntiedSwitch(CodeGenFunction &CGF) override { 285 if (OuterRegionInfo) 286 OuterRegionInfo->emitUntiedSwitch(CGF); 287 } 288 289 CodeGenFunction::CGCapturedStmtInfo *getOldCSI() const { return OldCSI; } 290 291 static bool classof(const CGCapturedStmtInfo *Info) { 292 return CGOpenMPRegionInfo::classof(Info) && 293 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == InlinedRegion; 294 } 295 296 ~CGOpenMPInlinedRegionInfo() override = default; 297 298 private: 299 /// CodeGen info about outer OpenMP region. 300 CodeGenFunction::CGCapturedStmtInfo *OldCSI; 301 CGOpenMPRegionInfo *OuterRegionInfo; 302 }; 303 304 /// API for captured statement code generation in OpenMP target 305 /// constructs. For this captures, implicit parameters are used instead of the 306 /// captured fields. The name of the target region has to be unique in a given 307 /// application so it is provided by the client, because only the client has 308 /// the information to generate that. 309 class CGOpenMPTargetRegionInfo final : public CGOpenMPRegionInfo { 310 public: 311 CGOpenMPTargetRegionInfo(const CapturedStmt &CS, 312 const RegionCodeGenTy &CodeGen, StringRef HelperName) 313 : CGOpenMPRegionInfo(CS, TargetRegion, CodeGen, OMPD_target, 314 /*HasCancel=*/false), 315 HelperName(HelperName) {} 316 317 /// This is unused for target regions because each starts executing 318 /// with a single thread. 319 const VarDecl *getThreadIDVariable() const override { return nullptr; } 320 321 /// Get the name of the capture helper. 322 StringRef getHelperName() const override { return HelperName; } 323 324 static bool classof(const CGCapturedStmtInfo *Info) { 325 return CGOpenMPRegionInfo::classof(Info) && 326 cast<CGOpenMPRegionInfo>(Info)->getRegionKind() == TargetRegion; 327 } 328 329 private: 330 StringRef HelperName; 331 }; 332 333 static void EmptyCodeGen(CodeGenFunction &, PrePostActionTy &) { 334 llvm_unreachable("No codegen for expressions"); 335 } 336 /// API for generation of expressions captured in a innermost OpenMP 337 /// region. 338 class CGOpenMPInnerExprInfo final : public CGOpenMPInlinedRegionInfo { 339 public: 340 CGOpenMPInnerExprInfo(CodeGenFunction &CGF, const CapturedStmt &CS) 341 : CGOpenMPInlinedRegionInfo(CGF.CapturedStmtInfo, EmptyCodeGen, 342 OMPD_unknown, 343 /*HasCancel=*/false), 344 PrivScope(CGF) { 345 // Make sure the globals captured in the provided statement are local by 346 // using the privatization logic. We assume the same variable is not 347 // captured more than once. 348 for (const auto &C : CS.captures()) { 349 if (!C.capturesVariable() && !C.capturesVariableByCopy()) 350 continue; 351 352 const VarDecl *VD = C.getCapturedVar(); 353 if (VD->isLocalVarDeclOrParm()) 354 continue; 355 356 DeclRefExpr DRE(const_cast<VarDecl *>(VD), 357 /*RefersToEnclosingVariableOrCapture=*/false, 358 VD->getType().getNonReferenceType(), VK_LValue, 359 C.getLocation()); 360 PrivScope.addPrivate( 361 VD, [&CGF, &DRE]() { return CGF.EmitLValue(&DRE).getAddress(); }); 362 } 363 (void)PrivScope.Privatize(); 364 } 365 366 /// Lookup the captured field decl for a variable. 367 const FieldDecl *lookup(const VarDecl *VD) const override { 368 if (const FieldDecl *FD = CGOpenMPInlinedRegionInfo::lookup(VD)) 369 return FD; 370 return nullptr; 371 } 372 373 /// Emit the captured statement body. 374 void EmitBody(CodeGenFunction &CGF, const Stmt *S) override { 375 llvm_unreachable("No body for expressions"); 376 } 377 378 /// Get a variable or parameter for storing global thread id 379 /// inside OpenMP construct. 380 const VarDecl *getThreadIDVariable() const override { 381 llvm_unreachable("No thread id for expressions"); 382 } 383 384 /// Get the name of the capture helper. 385 StringRef getHelperName() const override { 386 llvm_unreachable("No helper name for expressions"); 387 } 388 389 static bool classof(const CGCapturedStmtInfo *Info) { return false; } 390 391 private: 392 /// Private scope to capture global variables. 393 CodeGenFunction::OMPPrivateScope PrivScope; 394 }; 395 396 /// RAII for emitting code of OpenMP constructs. 397 class InlinedOpenMPRegionRAII { 398 CodeGenFunction &CGF; 399 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields; 400 FieldDecl *LambdaThisCaptureField = nullptr; 401 const CodeGen::CGBlockInfo *BlockInfo = nullptr; 402 403 public: 404 /// Constructs region for combined constructs. 405 /// \param CodeGen Code generation sequence for combined directives. Includes 406 /// a list of functions used for code generation of implicitly inlined 407 /// regions. 408 InlinedOpenMPRegionRAII(CodeGenFunction &CGF, const RegionCodeGenTy &CodeGen, 409 OpenMPDirectiveKind Kind, bool HasCancel) 410 : CGF(CGF) { 411 // Start emission for the construct. 412 CGF.CapturedStmtInfo = new CGOpenMPInlinedRegionInfo( 413 CGF.CapturedStmtInfo, CodeGen, Kind, HasCancel); 414 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); 415 LambdaThisCaptureField = CGF.LambdaThisCaptureField; 416 CGF.LambdaThisCaptureField = nullptr; 417 BlockInfo = CGF.BlockInfo; 418 CGF.BlockInfo = nullptr; 419 } 420 421 ~InlinedOpenMPRegionRAII() { 422 // Restore original CapturedStmtInfo only if we're done with code emission. 423 auto *OldCSI = 424 cast<CGOpenMPInlinedRegionInfo>(CGF.CapturedStmtInfo)->getOldCSI(); 425 delete CGF.CapturedStmtInfo; 426 CGF.CapturedStmtInfo = OldCSI; 427 std::swap(CGF.LambdaCaptureFields, LambdaCaptureFields); 428 CGF.LambdaThisCaptureField = LambdaThisCaptureField; 429 CGF.BlockInfo = BlockInfo; 430 } 431 }; 432 433 /// Values for bit flags used in the ident_t to describe the fields. 434 /// All enumeric elements are named and described in accordance with the code 435 /// from http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h 436 enum OpenMPLocationFlags : unsigned { 437 /// Use trampoline for internal microtask. 438 OMP_IDENT_IMD = 0x01, 439 /// Use c-style ident structure. 440 OMP_IDENT_KMPC = 0x02, 441 /// Atomic reduction option for kmpc_reduce. 442 OMP_ATOMIC_REDUCE = 0x10, 443 /// Explicit 'barrier' directive. 444 OMP_IDENT_BARRIER_EXPL = 0x20, 445 /// Implicit barrier in code. 446 OMP_IDENT_BARRIER_IMPL = 0x40, 447 /// Implicit barrier in 'for' directive. 448 OMP_IDENT_BARRIER_IMPL_FOR = 0x40, 449 /// Implicit barrier in 'sections' directive. 450 OMP_IDENT_BARRIER_IMPL_SECTIONS = 0xC0, 451 /// Implicit barrier in 'single' directive. 452 OMP_IDENT_BARRIER_IMPL_SINGLE = 0x140, 453 /// Call of __kmp_for_static_init for static loop. 454 OMP_IDENT_WORK_LOOP = 0x200, 455 /// Call of __kmp_for_static_init for sections. 456 OMP_IDENT_WORK_SECTIONS = 0x400, 457 /// Call of __kmp_for_static_init for distribute. 458 OMP_IDENT_WORK_DISTRIBUTE = 0x800, 459 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/OMP_IDENT_WORK_DISTRIBUTE) 460 }; 461 462 /// Describes ident structure that describes a source location. 463 /// All descriptions are taken from 464 /// http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h 465 /// Original structure: 466 /// typedef struct ident { 467 /// kmp_int32 reserved_1; /**< might be used in Fortran; 468 /// see above */ 469 /// kmp_int32 flags; /**< also f.flags; KMP_IDENT_xxx flags; 470 /// KMP_IDENT_KMPC identifies this union 471 /// member */ 472 /// kmp_int32 reserved_2; /**< not really used in Fortran any more; 473 /// see above */ 474 ///#if USE_ITT_BUILD 475 /// /* but currently used for storing 476 /// region-specific ITT */ 477 /// /* contextual information. */ 478 ///#endif /* USE_ITT_BUILD */ 479 /// kmp_int32 reserved_3; /**< source[4] in Fortran, do not use for 480 /// C++ */ 481 /// char const *psource; /**< String describing the source location. 482 /// The string is composed of semi-colon separated 483 // fields which describe the source file, 484 /// the function and a pair of line numbers that 485 /// delimit the construct. 486 /// */ 487 /// } ident_t; 488 enum IdentFieldIndex { 489 /// might be used in Fortran 490 IdentField_Reserved_1, 491 /// OMP_IDENT_xxx flags; OMP_IDENT_KMPC identifies this union member. 492 IdentField_Flags, 493 /// Not really used in Fortran any more 494 IdentField_Reserved_2, 495 /// Source[4] in Fortran, do not use for C++ 496 IdentField_Reserved_3, 497 /// String describing the source location. The string is composed of 498 /// semi-colon separated fields which describe the source file, the function 499 /// and a pair of line numbers that delimit the construct. 500 IdentField_PSource 501 }; 502 503 /// Schedule types for 'omp for' loops (these enumerators are taken from 504 /// the enum sched_type in kmp.h). 505 enum OpenMPSchedType { 506 /// Lower bound for default (unordered) versions. 507 OMP_sch_lower = 32, 508 OMP_sch_static_chunked = 33, 509 OMP_sch_static = 34, 510 OMP_sch_dynamic_chunked = 35, 511 OMP_sch_guided_chunked = 36, 512 OMP_sch_runtime = 37, 513 OMP_sch_auto = 38, 514 /// static with chunk adjustment (e.g., simd) 515 OMP_sch_static_balanced_chunked = 45, 516 /// Lower bound for 'ordered' versions. 517 OMP_ord_lower = 64, 518 OMP_ord_static_chunked = 65, 519 OMP_ord_static = 66, 520 OMP_ord_dynamic_chunked = 67, 521 OMP_ord_guided_chunked = 68, 522 OMP_ord_runtime = 69, 523 OMP_ord_auto = 70, 524 OMP_sch_default = OMP_sch_static, 525 /// dist_schedule types 526 OMP_dist_sch_static_chunked = 91, 527 OMP_dist_sch_static = 92, 528 /// Support for OpenMP 4.5 monotonic and nonmonotonic schedule modifiers. 529 /// Set if the monotonic schedule modifier was present. 530 OMP_sch_modifier_monotonic = (1 << 29), 531 /// Set if the nonmonotonic schedule modifier was present. 532 OMP_sch_modifier_nonmonotonic = (1 << 30), 533 }; 534 535 enum OpenMPRTLFunction { 536 /// Call to void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, 537 /// kmpc_micro microtask, ...); 538 OMPRTL__kmpc_fork_call, 539 /// Call to void *__kmpc_threadprivate_cached(ident_t *loc, 540 /// kmp_int32 global_tid, void *data, size_t size, void ***cache); 541 OMPRTL__kmpc_threadprivate_cached, 542 /// Call to void __kmpc_threadprivate_register( ident_t *, 543 /// void *data, kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor); 544 OMPRTL__kmpc_threadprivate_register, 545 // Call to __kmpc_int32 kmpc_global_thread_num(ident_t *loc); 546 OMPRTL__kmpc_global_thread_num, 547 // Call to void __kmpc_critical(ident_t *loc, kmp_int32 global_tid, 548 // kmp_critical_name *crit); 549 OMPRTL__kmpc_critical, 550 // Call to void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 551 // global_tid, kmp_critical_name *crit, uintptr_t hint); 552 OMPRTL__kmpc_critical_with_hint, 553 // Call to void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, 554 // kmp_critical_name *crit); 555 OMPRTL__kmpc_end_critical, 556 // Call to kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32 557 // global_tid); 558 OMPRTL__kmpc_cancel_barrier, 559 // Call to void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid); 560 OMPRTL__kmpc_barrier, 561 // Call to void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid); 562 OMPRTL__kmpc_for_static_fini, 563 // Call to void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 564 // global_tid); 565 OMPRTL__kmpc_serialized_parallel, 566 // Call to void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 567 // global_tid); 568 OMPRTL__kmpc_end_serialized_parallel, 569 // Call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, 570 // kmp_int32 num_threads); 571 OMPRTL__kmpc_push_num_threads, 572 // Call to void __kmpc_flush(ident_t *loc); 573 OMPRTL__kmpc_flush, 574 // Call to kmp_int32 __kmpc_master(ident_t *, kmp_int32 global_tid); 575 OMPRTL__kmpc_master, 576 // Call to void __kmpc_end_master(ident_t *, kmp_int32 global_tid); 577 OMPRTL__kmpc_end_master, 578 // Call to kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid, 579 // int end_part); 580 OMPRTL__kmpc_omp_taskyield, 581 // Call to kmp_int32 __kmpc_single(ident_t *, kmp_int32 global_tid); 582 OMPRTL__kmpc_single, 583 // Call to void __kmpc_end_single(ident_t *, kmp_int32 global_tid); 584 OMPRTL__kmpc_end_single, 585 // Call to kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, 586 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 587 // kmp_routine_entry_t *task_entry); 588 OMPRTL__kmpc_omp_task_alloc, 589 // Call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t * 590 // new_task); 591 OMPRTL__kmpc_omp_task, 592 // Call to void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid, 593 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *), 594 // kmp_int32 didit); 595 OMPRTL__kmpc_copyprivate, 596 // Call to kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid, 597 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void 598 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck); 599 OMPRTL__kmpc_reduce, 600 // Call to kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32 601 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, 602 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name 603 // *lck); 604 OMPRTL__kmpc_reduce_nowait, 605 // Call to void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid, 606 // kmp_critical_name *lck); 607 OMPRTL__kmpc_end_reduce, 608 // Call to void __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid, 609 // kmp_critical_name *lck); 610 OMPRTL__kmpc_end_reduce_nowait, 611 // Call to void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid, 612 // kmp_task_t * new_task); 613 OMPRTL__kmpc_omp_task_begin_if0, 614 // Call to void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid, 615 // kmp_task_t * new_task); 616 OMPRTL__kmpc_omp_task_complete_if0, 617 // Call to void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid); 618 OMPRTL__kmpc_ordered, 619 // Call to void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid); 620 OMPRTL__kmpc_end_ordered, 621 // Call to kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 622 // global_tid); 623 OMPRTL__kmpc_omp_taskwait, 624 // Call to void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid); 625 OMPRTL__kmpc_taskgroup, 626 // Call to void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid); 627 OMPRTL__kmpc_end_taskgroup, 628 // Call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, 629 // int proc_bind); 630 OMPRTL__kmpc_push_proc_bind, 631 // Call to kmp_int32 __kmpc_omp_task_with_deps(ident_t *loc_ref, kmp_int32 632 // gtid, kmp_task_t * new_task, kmp_int32 ndeps, kmp_depend_info_t 633 // *dep_list, kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list); 634 OMPRTL__kmpc_omp_task_with_deps, 635 // Call to void __kmpc_omp_wait_deps(ident_t *loc_ref, kmp_int32 636 // gtid, kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 637 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); 638 OMPRTL__kmpc_omp_wait_deps, 639 // Call to kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32 640 // global_tid, kmp_int32 cncl_kind); 641 OMPRTL__kmpc_cancellationpoint, 642 // Call to kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid, 643 // kmp_int32 cncl_kind); 644 OMPRTL__kmpc_cancel, 645 // Call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 global_tid, 646 // kmp_int32 num_teams, kmp_int32 thread_limit); 647 OMPRTL__kmpc_push_num_teams, 648 // Call to void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro 649 // microtask, ...); 650 OMPRTL__kmpc_fork_teams, 651 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int 652 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int 653 // sched, kmp_uint64 grainsize, void *task_dup); 654 OMPRTL__kmpc_taskloop, 655 // Call to void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32 656 // num_dims, struct kmp_dim *dims); 657 OMPRTL__kmpc_doacross_init, 658 // Call to void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid); 659 OMPRTL__kmpc_doacross_fini, 660 // Call to void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64 661 // *vec); 662 OMPRTL__kmpc_doacross_post, 663 // Call to void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64 664 // *vec); 665 OMPRTL__kmpc_doacross_wait, 666 // Call to void *__kmpc_task_reduction_init(int gtid, int num_data, void 667 // *data); 668 OMPRTL__kmpc_task_reduction_init, 669 // Call to void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void 670 // *d); 671 OMPRTL__kmpc_task_reduction_get_th_data, 672 673 // 674 // Offloading related calls 675 // 676 // Call to int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t 677 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 678 // *arg_types); 679 OMPRTL__tgt_target, 680 // Call to int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr, 681 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 682 // *arg_types); 683 OMPRTL__tgt_target_nowait, 684 // Call to int32_t __tgt_target_teams(int64_t device_id, void *host_ptr, 685 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 686 // *arg_types, int32_t num_teams, int32_t thread_limit); 687 OMPRTL__tgt_target_teams, 688 // Call to int32_t __tgt_target_teams_nowait(int64_t device_id, void 689 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t 690 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit); 691 OMPRTL__tgt_target_teams_nowait, 692 // Call to void __tgt_register_lib(__tgt_bin_desc *desc); 693 OMPRTL__tgt_register_lib, 694 // Call to void __tgt_unregister_lib(__tgt_bin_desc *desc); 695 OMPRTL__tgt_unregister_lib, 696 // Call to void __tgt_target_data_begin(int64_t device_id, int32_t arg_num, 697 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 698 OMPRTL__tgt_target_data_begin, 699 // Call to void __tgt_target_data_begin_nowait(int64_t device_id, int32_t 700 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 701 // *arg_types); 702 OMPRTL__tgt_target_data_begin_nowait, 703 // Call to void __tgt_target_data_end(int64_t device_id, int32_t arg_num, 704 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 705 OMPRTL__tgt_target_data_end, 706 // Call to void __tgt_target_data_end_nowait(int64_t device_id, int32_t 707 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 708 // *arg_types); 709 OMPRTL__tgt_target_data_end_nowait, 710 // Call to void __tgt_target_data_update(int64_t device_id, int32_t arg_num, 711 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 712 OMPRTL__tgt_target_data_update, 713 // Call to void __tgt_target_data_update_nowait(int64_t device_id, int32_t 714 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 715 // *arg_types); 716 OMPRTL__tgt_target_data_update_nowait, 717 }; 718 719 /// A basic class for pre|post-action for advanced codegen sequence for OpenMP 720 /// region. 721 class CleanupTy final : public EHScopeStack::Cleanup { 722 PrePostActionTy *Action; 723 724 public: 725 explicit CleanupTy(PrePostActionTy *Action) : Action(Action) {} 726 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { 727 if (!CGF.HaveInsertPoint()) 728 return; 729 Action->Exit(CGF); 730 } 731 }; 732 733 } // anonymous namespace 734 735 void RegionCodeGenTy::operator()(CodeGenFunction &CGF) const { 736 CodeGenFunction::RunCleanupsScope Scope(CGF); 737 if (PrePostAction) { 738 CGF.EHStack.pushCleanup<CleanupTy>(NormalAndEHCleanup, PrePostAction); 739 Callback(CodeGen, CGF, *PrePostAction); 740 } else { 741 PrePostActionTy Action; 742 Callback(CodeGen, CGF, Action); 743 } 744 } 745 746 /// Check if the combiner is a call to UDR combiner and if it is so return the 747 /// UDR decl used for reduction. 748 static const OMPDeclareReductionDecl * 749 getReductionInit(const Expr *ReductionOp) { 750 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) 751 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) 752 if (const auto *DRE = 753 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) 754 if (const auto *DRD = dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) 755 return DRD; 756 return nullptr; 757 } 758 759 static void emitInitWithReductionInitializer(CodeGenFunction &CGF, 760 const OMPDeclareReductionDecl *DRD, 761 const Expr *InitOp, 762 Address Private, Address Original, 763 QualType Ty) { 764 if (DRD->getInitializer()) { 765 std::pair<llvm::Function *, llvm::Function *> Reduction = 766 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); 767 const auto *CE = cast<CallExpr>(InitOp); 768 const auto *OVE = cast<OpaqueValueExpr>(CE->getCallee()); 769 const Expr *LHS = CE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 770 const Expr *RHS = CE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 771 const auto *LHSDRE = 772 cast<DeclRefExpr>(cast<UnaryOperator>(LHS)->getSubExpr()); 773 const auto *RHSDRE = 774 cast<DeclRefExpr>(cast<UnaryOperator>(RHS)->getSubExpr()); 775 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 776 PrivateScope.addPrivate(cast<VarDecl>(LHSDRE->getDecl()), 777 [=]() { return Private; }); 778 PrivateScope.addPrivate(cast<VarDecl>(RHSDRE->getDecl()), 779 [=]() { return Original; }); 780 (void)PrivateScope.Privatize(); 781 RValue Func = RValue::get(Reduction.second); 782 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); 783 CGF.EmitIgnoredExpr(InitOp); 784 } else { 785 llvm::Constant *Init = CGF.CGM.EmitNullConstant(Ty); 786 std::string Name = CGF.CGM.getOpenMPRuntime().getName({"init"}); 787 auto *GV = new llvm::GlobalVariable( 788 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true, 789 llvm::GlobalValue::PrivateLinkage, Init, Name); 790 LValue LV = CGF.MakeNaturalAlignAddrLValue(GV, Ty); 791 RValue InitRVal; 792 switch (CGF.getEvaluationKind(Ty)) { 793 case TEK_Scalar: 794 InitRVal = CGF.EmitLoadOfLValue(LV, DRD->getLocation()); 795 break; 796 case TEK_Complex: 797 InitRVal = 798 RValue::getComplex(CGF.EmitLoadOfComplex(LV, DRD->getLocation())); 799 break; 800 case TEK_Aggregate: 801 InitRVal = RValue::getAggregate(LV.getAddress()); 802 break; 803 } 804 OpaqueValueExpr OVE(DRD->getLocation(), Ty, VK_RValue); 805 CodeGenFunction::OpaqueValueMapping OpaqueMap(CGF, &OVE, InitRVal); 806 CGF.EmitAnyExprToMem(&OVE, Private, Ty.getQualifiers(), 807 /*IsInitializer=*/false); 808 } 809 } 810 811 /// Emit initialization of arrays of complex types. 812 /// \param DestAddr Address of the array. 813 /// \param Type Type of array. 814 /// \param Init Initial expression of array. 815 /// \param SrcAddr Address of the original array. 816 static void EmitOMPAggregateInit(CodeGenFunction &CGF, Address DestAddr, 817 QualType Type, bool EmitDeclareReductionInit, 818 const Expr *Init, 819 const OMPDeclareReductionDecl *DRD, 820 Address SrcAddr = Address::invalid()) { 821 // Perform element-by-element initialization. 822 QualType ElementTy; 823 824 // Drill down to the base element type on both arrays. 825 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); 826 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, DestAddr); 827 DestAddr = 828 CGF.Builder.CreateElementBitCast(DestAddr, DestAddr.getElementType()); 829 if (DRD) 830 SrcAddr = 831 CGF.Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 832 833 llvm::Value *SrcBegin = nullptr; 834 if (DRD) 835 SrcBegin = SrcAddr.getPointer(); 836 llvm::Value *DestBegin = DestAddr.getPointer(); 837 // Cast from pointer to array type to pointer to single element. 838 llvm::Value *DestEnd = CGF.Builder.CreateGEP(DestBegin, NumElements); 839 // The basic structure here is a while-do loop. 840 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arrayinit.body"); 841 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arrayinit.done"); 842 llvm::Value *IsEmpty = 843 CGF.Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arrayinit.isempty"); 844 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 845 846 // Enter the loop body, making that address the current address. 847 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); 848 CGF.EmitBlock(BodyBB); 849 850 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); 851 852 llvm::PHINode *SrcElementPHI = nullptr; 853 Address SrcElementCurrent = Address::invalid(); 854 if (DRD) { 855 SrcElementPHI = CGF.Builder.CreatePHI(SrcBegin->getType(), 2, 856 "omp.arraycpy.srcElementPast"); 857 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 858 SrcElementCurrent = 859 Address(SrcElementPHI, 860 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 861 } 862 llvm::PHINode *DestElementPHI = CGF.Builder.CreatePHI( 863 DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 864 DestElementPHI->addIncoming(DestBegin, EntryBB); 865 Address DestElementCurrent = 866 Address(DestElementPHI, 867 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 868 869 // Emit copy. 870 { 871 CodeGenFunction::RunCleanupsScope InitScope(CGF); 872 if (EmitDeclareReductionInit) { 873 emitInitWithReductionInitializer(CGF, DRD, Init, DestElementCurrent, 874 SrcElementCurrent, ElementTy); 875 } else 876 CGF.EmitAnyExprToMem(Init, DestElementCurrent, ElementTy.getQualifiers(), 877 /*IsInitializer=*/false); 878 } 879 880 if (DRD) { 881 // Shift the address forward by one element. 882 llvm::Value *SrcElementNext = CGF.Builder.CreateConstGEP1_32( 883 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 884 SrcElementPHI->addIncoming(SrcElementNext, CGF.Builder.GetInsertBlock()); 885 } 886 887 // Shift the address forward by one element. 888 llvm::Value *DestElementNext = CGF.Builder.CreateConstGEP1_32( 889 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 890 // Check whether we've reached the end. 891 llvm::Value *Done = 892 CGF.Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 893 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); 894 DestElementPHI->addIncoming(DestElementNext, CGF.Builder.GetInsertBlock()); 895 896 // Done. 897 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 898 } 899 900 LValue ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, const Expr *E) { 901 return CGF.EmitOMPSharedLValue(E); 902 } 903 904 LValue ReductionCodeGen::emitSharedLValueUB(CodeGenFunction &CGF, 905 const Expr *E) { 906 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(E)) 907 return CGF.EmitOMPArraySectionExpr(OASE, /*IsLowerBound=*/false); 908 return LValue(); 909 } 910 911 void ReductionCodeGen::emitAggregateInitialization( 912 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, 913 const OMPDeclareReductionDecl *DRD) { 914 // Emit VarDecl with copy init for arrays. 915 // Get the address of the original variable captured in current 916 // captured region. 917 const auto *PrivateVD = 918 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 919 bool EmitDeclareReductionInit = 920 DRD && (DRD->getInitializer() || !PrivateVD->hasInit()); 921 EmitOMPAggregateInit(CGF, PrivateAddr, PrivateVD->getType(), 922 EmitDeclareReductionInit, 923 EmitDeclareReductionInit ? ClausesData[N].ReductionOp 924 : PrivateVD->getInit(), 925 DRD, SharedLVal.getAddress()); 926 } 927 928 ReductionCodeGen::ReductionCodeGen(ArrayRef<const Expr *> Shareds, 929 ArrayRef<const Expr *> Privates, 930 ArrayRef<const Expr *> ReductionOps) { 931 ClausesData.reserve(Shareds.size()); 932 SharedAddresses.reserve(Shareds.size()); 933 Sizes.reserve(Shareds.size()); 934 BaseDecls.reserve(Shareds.size()); 935 auto IPriv = Privates.begin(); 936 auto IRed = ReductionOps.begin(); 937 for (const Expr *Ref : Shareds) { 938 ClausesData.emplace_back(Ref, *IPriv, *IRed); 939 std::advance(IPriv, 1); 940 std::advance(IRed, 1); 941 } 942 } 943 944 void ReductionCodeGen::emitSharedLValue(CodeGenFunction &CGF, unsigned N) { 945 assert(SharedAddresses.size() == N && 946 "Number of generated lvalues must be exactly N."); 947 LValue First = emitSharedLValue(CGF, ClausesData[N].Ref); 948 LValue Second = emitSharedLValueUB(CGF, ClausesData[N].Ref); 949 SharedAddresses.emplace_back(First, Second); 950 } 951 952 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N) { 953 const auto *PrivateVD = 954 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 955 QualType PrivateType = PrivateVD->getType(); 956 bool AsArraySection = isa<OMPArraySectionExpr>(ClausesData[N].Ref); 957 if (!PrivateType->isVariablyModifiedType()) { 958 Sizes.emplace_back( 959 CGF.getTypeSize( 960 SharedAddresses[N].first.getType().getNonReferenceType()), 961 nullptr); 962 return; 963 } 964 llvm::Value *Size; 965 llvm::Value *SizeInChars; 966 auto *ElemType = 967 cast<llvm::PointerType>(SharedAddresses[N].first.getPointer()->getType()) 968 ->getElementType(); 969 auto *ElemSizeOf = llvm::ConstantExpr::getSizeOf(ElemType); 970 if (AsArraySection) { 971 Size = CGF.Builder.CreatePtrDiff(SharedAddresses[N].second.getPointer(), 972 SharedAddresses[N].first.getPointer()); 973 Size = CGF.Builder.CreateNUWAdd( 974 Size, llvm::ConstantInt::get(Size->getType(), /*V=*/1)); 975 SizeInChars = CGF.Builder.CreateNUWMul(Size, ElemSizeOf); 976 } else { 977 SizeInChars = CGF.getTypeSize( 978 SharedAddresses[N].first.getType().getNonReferenceType()); 979 Size = CGF.Builder.CreateExactUDiv(SizeInChars, ElemSizeOf); 980 } 981 Sizes.emplace_back(SizeInChars, Size); 982 CodeGenFunction::OpaqueValueMapping OpaqueMap( 983 CGF, 984 cast<OpaqueValueExpr>( 985 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), 986 RValue::get(Size)); 987 CGF.EmitVariablyModifiedType(PrivateType); 988 } 989 990 void ReductionCodeGen::emitAggregateType(CodeGenFunction &CGF, unsigned N, 991 llvm::Value *Size) { 992 const auto *PrivateVD = 993 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 994 QualType PrivateType = PrivateVD->getType(); 995 if (!PrivateType->isVariablyModifiedType()) { 996 assert(!Size && !Sizes[N].second && 997 "Size should be nullptr for non-variably modified reduction " 998 "items."); 999 return; 1000 } 1001 CodeGenFunction::OpaqueValueMapping OpaqueMap( 1002 CGF, 1003 cast<OpaqueValueExpr>( 1004 CGF.getContext().getAsVariableArrayType(PrivateType)->getSizeExpr()), 1005 RValue::get(Size)); 1006 CGF.EmitVariablyModifiedType(PrivateType); 1007 } 1008 1009 void ReductionCodeGen::emitInitialization( 1010 CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, 1011 llvm::function_ref<bool(CodeGenFunction &)> DefaultInit) { 1012 assert(SharedAddresses.size() > N && "No variable was generated"); 1013 const auto *PrivateVD = 1014 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 1015 const OMPDeclareReductionDecl *DRD = 1016 getReductionInit(ClausesData[N].ReductionOp); 1017 QualType PrivateType = PrivateVD->getType(); 1018 PrivateAddr = CGF.Builder.CreateElementBitCast( 1019 PrivateAddr, CGF.ConvertTypeForMem(PrivateType)); 1020 QualType SharedType = SharedAddresses[N].first.getType(); 1021 SharedLVal = CGF.MakeAddrLValue( 1022 CGF.Builder.CreateElementBitCast(SharedLVal.getAddress(), 1023 CGF.ConvertTypeForMem(SharedType)), 1024 SharedType, SharedAddresses[N].first.getBaseInfo(), 1025 CGF.CGM.getTBAAInfoForSubobject(SharedAddresses[N].first, SharedType)); 1026 if (CGF.getContext().getAsArrayType(PrivateVD->getType())) { 1027 emitAggregateInitialization(CGF, N, PrivateAddr, SharedLVal, DRD); 1028 } else if (DRD && (DRD->getInitializer() || !PrivateVD->hasInit())) { 1029 emitInitWithReductionInitializer(CGF, DRD, ClausesData[N].ReductionOp, 1030 PrivateAddr, SharedLVal.getAddress(), 1031 SharedLVal.getType()); 1032 } else if (!DefaultInit(CGF) && PrivateVD->hasInit() && 1033 !CGF.isTrivialInitializer(PrivateVD->getInit())) { 1034 CGF.EmitAnyExprToMem(PrivateVD->getInit(), PrivateAddr, 1035 PrivateVD->getType().getQualifiers(), 1036 /*IsInitializer=*/false); 1037 } 1038 } 1039 1040 bool ReductionCodeGen::needCleanups(unsigned N) { 1041 const auto *PrivateVD = 1042 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 1043 QualType PrivateType = PrivateVD->getType(); 1044 QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); 1045 return DTorKind != QualType::DK_none; 1046 } 1047 1048 void ReductionCodeGen::emitCleanups(CodeGenFunction &CGF, unsigned N, 1049 Address PrivateAddr) { 1050 const auto *PrivateVD = 1051 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Private)->getDecl()); 1052 QualType PrivateType = PrivateVD->getType(); 1053 QualType::DestructionKind DTorKind = PrivateType.isDestructedType(); 1054 if (needCleanups(N)) { 1055 PrivateAddr = CGF.Builder.CreateElementBitCast( 1056 PrivateAddr, CGF.ConvertTypeForMem(PrivateType)); 1057 CGF.pushDestroy(DTorKind, PrivateAddr, PrivateType); 1058 } 1059 } 1060 1061 static LValue loadToBegin(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, 1062 LValue BaseLV) { 1063 BaseTy = BaseTy.getNonReferenceType(); 1064 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && 1065 !CGF.getContext().hasSameType(BaseTy, ElTy)) { 1066 if (const auto *PtrTy = BaseTy->getAs<PointerType>()) { 1067 BaseLV = CGF.EmitLoadOfPointerLValue(BaseLV.getAddress(), PtrTy); 1068 } else { 1069 LValue RefLVal = CGF.MakeAddrLValue(BaseLV.getAddress(), BaseTy); 1070 BaseLV = CGF.EmitLoadOfReferenceLValue(RefLVal); 1071 } 1072 BaseTy = BaseTy->getPointeeType(); 1073 } 1074 return CGF.MakeAddrLValue( 1075 CGF.Builder.CreateElementBitCast(BaseLV.getAddress(), 1076 CGF.ConvertTypeForMem(ElTy)), 1077 BaseLV.getType(), BaseLV.getBaseInfo(), 1078 CGF.CGM.getTBAAInfoForSubobject(BaseLV, BaseLV.getType())); 1079 } 1080 1081 static Address castToBase(CodeGenFunction &CGF, QualType BaseTy, QualType ElTy, 1082 llvm::Type *BaseLVType, CharUnits BaseLVAlignment, 1083 llvm::Value *Addr) { 1084 Address Tmp = Address::invalid(); 1085 Address TopTmp = Address::invalid(); 1086 Address MostTopTmp = Address::invalid(); 1087 BaseTy = BaseTy.getNonReferenceType(); 1088 while ((BaseTy->isPointerType() || BaseTy->isReferenceType()) && 1089 !CGF.getContext().hasSameType(BaseTy, ElTy)) { 1090 Tmp = CGF.CreateMemTemp(BaseTy); 1091 if (TopTmp.isValid()) 1092 CGF.Builder.CreateStore(Tmp.getPointer(), TopTmp); 1093 else 1094 MostTopTmp = Tmp; 1095 TopTmp = Tmp; 1096 BaseTy = BaseTy->getPointeeType(); 1097 } 1098 llvm::Type *Ty = BaseLVType; 1099 if (Tmp.isValid()) 1100 Ty = Tmp.getElementType(); 1101 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, Ty); 1102 if (Tmp.isValid()) { 1103 CGF.Builder.CreateStore(Addr, Tmp); 1104 return MostTopTmp; 1105 } 1106 return Address(Addr, BaseLVAlignment); 1107 } 1108 1109 static const VarDecl *getBaseDecl(const Expr *Ref, const DeclRefExpr *&DE) { 1110 const VarDecl *OrigVD = nullptr; 1111 if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Ref)) { 1112 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 1113 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 1114 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 1115 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 1116 Base = TempASE->getBase()->IgnoreParenImpCasts(); 1117 DE = cast<DeclRefExpr>(Base); 1118 OrigVD = cast<VarDecl>(DE->getDecl()); 1119 } else if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Ref)) { 1120 const Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 1121 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 1122 Base = TempASE->getBase()->IgnoreParenImpCasts(); 1123 DE = cast<DeclRefExpr>(Base); 1124 OrigVD = cast<VarDecl>(DE->getDecl()); 1125 } 1126 return OrigVD; 1127 } 1128 1129 Address ReductionCodeGen::adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, 1130 Address PrivateAddr) { 1131 const DeclRefExpr *DE; 1132 if (const VarDecl *OrigVD = ::getBaseDecl(ClausesData[N].Ref, DE)) { 1133 BaseDecls.emplace_back(OrigVD); 1134 LValue OriginalBaseLValue = CGF.EmitLValue(DE); 1135 LValue BaseLValue = 1136 loadToBegin(CGF, OrigVD->getType(), SharedAddresses[N].first.getType(), 1137 OriginalBaseLValue); 1138 llvm::Value *Adjustment = CGF.Builder.CreatePtrDiff( 1139 BaseLValue.getPointer(), SharedAddresses[N].first.getPointer()); 1140 llvm::Value *PrivatePointer = 1141 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 1142 PrivateAddr.getPointer(), 1143 SharedAddresses[N].first.getAddress().getType()); 1144 llvm::Value *Ptr = CGF.Builder.CreateGEP(PrivatePointer, Adjustment); 1145 return castToBase(CGF, OrigVD->getType(), 1146 SharedAddresses[N].first.getType(), 1147 OriginalBaseLValue.getAddress().getType(), 1148 OriginalBaseLValue.getAlignment(), Ptr); 1149 } 1150 BaseDecls.emplace_back( 1151 cast<VarDecl>(cast<DeclRefExpr>(ClausesData[N].Ref)->getDecl())); 1152 return PrivateAddr; 1153 } 1154 1155 bool ReductionCodeGen::usesReductionInitializer(unsigned N) const { 1156 const OMPDeclareReductionDecl *DRD = 1157 getReductionInit(ClausesData[N].ReductionOp); 1158 return DRD && DRD->getInitializer(); 1159 } 1160 1161 LValue CGOpenMPRegionInfo::getThreadIDVariableLValue(CodeGenFunction &CGF) { 1162 return CGF.EmitLoadOfPointerLValue( 1163 CGF.GetAddrOfLocalVar(getThreadIDVariable()), 1164 getThreadIDVariable()->getType()->castAs<PointerType>()); 1165 } 1166 1167 void CGOpenMPRegionInfo::EmitBody(CodeGenFunction &CGF, const Stmt * /*S*/) { 1168 if (!CGF.HaveInsertPoint()) 1169 return; 1170 // 1.2.2 OpenMP Language Terminology 1171 // Structured block - An executable statement with a single entry at the 1172 // top and a single exit at the bottom. 1173 // The point of exit cannot be a branch out of the structured block. 1174 // longjmp() and throw() must not violate the entry/exit criteria. 1175 CGF.EHStack.pushTerminate(); 1176 CodeGen(CGF); 1177 CGF.EHStack.popTerminate(); 1178 } 1179 1180 LValue CGOpenMPTaskOutlinedRegionInfo::getThreadIDVariableLValue( 1181 CodeGenFunction &CGF) { 1182 return CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(getThreadIDVariable()), 1183 getThreadIDVariable()->getType(), 1184 AlignmentSource::Decl); 1185 } 1186 1187 static FieldDecl *addFieldToRecordDecl(ASTContext &C, DeclContext *DC, 1188 QualType FieldTy) { 1189 auto *Field = FieldDecl::Create( 1190 C, DC, SourceLocation(), SourceLocation(), /*Id=*/nullptr, FieldTy, 1191 C.getTrivialTypeSourceInfo(FieldTy, SourceLocation()), 1192 /*BW=*/nullptr, /*Mutable=*/false, /*InitStyle=*/ICIS_NoInit); 1193 Field->setAccess(AS_public); 1194 DC->addDecl(Field); 1195 return Field; 1196 } 1197 1198 CGOpenMPRuntime::CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator, 1199 StringRef Separator) 1200 : CGM(CGM), FirstSeparator(FirstSeparator), Separator(Separator), 1201 OffloadEntriesInfoManager(CGM) { 1202 ASTContext &C = CGM.getContext(); 1203 RecordDecl *RD = C.buildImplicitRecord("ident_t"); 1204 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1205 RD->startDefinition(); 1206 // reserved_1 1207 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1208 // flags 1209 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1210 // reserved_2 1211 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1212 // reserved_3 1213 addFieldToRecordDecl(C, RD, KmpInt32Ty); 1214 // psource 1215 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 1216 RD->completeDefinition(); 1217 IdentQTy = C.getRecordType(RD); 1218 IdentTy = CGM.getTypes().ConvertRecordDeclType(RD); 1219 KmpCriticalNameTy = llvm::ArrayType::get(CGM.Int32Ty, /*NumElements*/ 8); 1220 1221 loadOffloadInfoMetadata(); 1222 } 1223 1224 void CGOpenMPRuntime::clear() { 1225 InternalVars.clear(); 1226 } 1227 1228 std::string CGOpenMPRuntime::getName(ArrayRef<StringRef> Parts) const { 1229 SmallString<128> Buffer; 1230 llvm::raw_svector_ostream OS(Buffer); 1231 StringRef Sep = FirstSeparator; 1232 for (StringRef Part : Parts) { 1233 OS << Sep << Part; 1234 Sep = Separator; 1235 } 1236 return OS.str(); 1237 } 1238 1239 static llvm::Function * 1240 emitCombinerOrInitializer(CodeGenModule &CGM, QualType Ty, 1241 const Expr *CombinerInitializer, const VarDecl *In, 1242 const VarDecl *Out, bool IsCombiner) { 1243 // void .omp_combiner.(Ty *in, Ty *out); 1244 ASTContext &C = CGM.getContext(); 1245 QualType PtrTy = C.getPointerType(Ty).withRestrict(); 1246 FunctionArgList Args; 1247 ImplicitParamDecl OmpOutParm(C, /*DC=*/nullptr, Out->getLocation(), 1248 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); 1249 ImplicitParamDecl OmpInParm(C, /*DC=*/nullptr, In->getLocation(), 1250 /*Id=*/nullptr, PtrTy, ImplicitParamDecl::Other); 1251 Args.push_back(&OmpOutParm); 1252 Args.push_back(&OmpInParm); 1253 const CGFunctionInfo &FnInfo = 1254 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 1255 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 1256 std::string Name = CGM.getOpenMPRuntime().getName( 1257 {IsCombiner ? "omp_combiner" : "omp_initializer", ""}); 1258 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 1259 Name, &CGM.getModule()); 1260 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 1261 Fn->removeFnAttr(llvm::Attribute::NoInline); 1262 Fn->removeFnAttr(llvm::Attribute::OptimizeNone); 1263 Fn->addFnAttr(llvm::Attribute::AlwaysInline); 1264 CodeGenFunction CGF(CGM); 1265 // Map "T omp_in;" variable to "*omp_in_parm" value in all expressions. 1266 // Map "T omp_out;" variable to "*omp_out_parm" value in all expressions. 1267 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, In->getLocation(), 1268 Out->getLocation()); 1269 CodeGenFunction::OMPPrivateScope Scope(CGF); 1270 Address AddrIn = CGF.GetAddrOfLocalVar(&OmpInParm); 1271 Scope.addPrivate(In, [&CGF, AddrIn, PtrTy]() { 1272 return CGF.EmitLoadOfPointerLValue(AddrIn, PtrTy->castAs<PointerType>()) 1273 .getAddress(); 1274 }); 1275 Address AddrOut = CGF.GetAddrOfLocalVar(&OmpOutParm); 1276 Scope.addPrivate(Out, [&CGF, AddrOut, PtrTy]() { 1277 return CGF.EmitLoadOfPointerLValue(AddrOut, PtrTy->castAs<PointerType>()) 1278 .getAddress(); 1279 }); 1280 (void)Scope.Privatize(); 1281 if (!IsCombiner && Out->hasInit() && 1282 !CGF.isTrivialInitializer(Out->getInit())) { 1283 CGF.EmitAnyExprToMem(Out->getInit(), CGF.GetAddrOfLocalVar(Out), 1284 Out->getType().getQualifiers(), 1285 /*IsInitializer=*/true); 1286 } 1287 if (CombinerInitializer) 1288 CGF.EmitIgnoredExpr(CombinerInitializer); 1289 Scope.ForceCleanup(); 1290 CGF.FinishFunction(); 1291 return Fn; 1292 } 1293 1294 void CGOpenMPRuntime::emitUserDefinedReduction( 1295 CodeGenFunction *CGF, const OMPDeclareReductionDecl *D) { 1296 if (UDRMap.count(D) > 0) 1297 return; 1298 llvm::Function *Combiner = emitCombinerOrInitializer( 1299 CGM, D->getType(), D->getCombiner(), 1300 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerIn())->getDecl()), 1301 cast<VarDecl>(cast<DeclRefExpr>(D->getCombinerOut())->getDecl()), 1302 /*IsCombiner=*/true); 1303 llvm::Function *Initializer = nullptr; 1304 if (const Expr *Init = D->getInitializer()) { 1305 Initializer = emitCombinerOrInitializer( 1306 CGM, D->getType(), 1307 D->getInitializerKind() == OMPDeclareReductionDecl::CallInit ? Init 1308 : nullptr, 1309 cast<VarDecl>(cast<DeclRefExpr>(D->getInitOrig())->getDecl()), 1310 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl()), 1311 /*IsCombiner=*/false); 1312 } 1313 UDRMap.try_emplace(D, Combiner, Initializer); 1314 if (CGF) { 1315 auto &Decls = FunctionUDRMap.FindAndConstruct(CGF->CurFn); 1316 Decls.second.push_back(D); 1317 } 1318 } 1319 1320 std::pair<llvm::Function *, llvm::Function *> 1321 CGOpenMPRuntime::getUserDefinedReduction(const OMPDeclareReductionDecl *D) { 1322 auto I = UDRMap.find(D); 1323 if (I != UDRMap.end()) 1324 return I->second; 1325 emitUserDefinedReduction(/*CGF=*/nullptr, D); 1326 return UDRMap.lookup(D); 1327 } 1328 1329 static llvm::Value *emitParallelOrTeamsOutlinedFunction( 1330 CodeGenModule &CGM, const OMPExecutableDirective &D, const CapturedStmt *CS, 1331 const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, 1332 const StringRef OutlinedHelperName, const RegionCodeGenTy &CodeGen) { 1333 assert(ThreadIDVar->getType()->isPointerType() && 1334 "thread id variable must be of type kmp_int32 *"); 1335 CodeGenFunction CGF(CGM, true); 1336 bool HasCancel = false; 1337 if (const auto *OPD = dyn_cast<OMPParallelDirective>(&D)) 1338 HasCancel = OPD->hasCancel(); 1339 else if (const auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&D)) 1340 HasCancel = OPSD->hasCancel(); 1341 else if (const auto *OPFD = dyn_cast<OMPParallelForDirective>(&D)) 1342 HasCancel = OPFD->hasCancel(); 1343 else if (const auto *OPFD = dyn_cast<OMPTargetParallelForDirective>(&D)) 1344 HasCancel = OPFD->hasCancel(); 1345 else if (const auto *OPFD = dyn_cast<OMPDistributeParallelForDirective>(&D)) 1346 HasCancel = OPFD->hasCancel(); 1347 else if (const auto *OPFD = 1348 dyn_cast<OMPTeamsDistributeParallelForDirective>(&D)) 1349 HasCancel = OPFD->hasCancel(); 1350 else if (const auto *OPFD = 1351 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&D)) 1352 HasCancel = OPFD->hasCancel(); 1353 CGOpenMPOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, InnermostKind, 1354 HasCancel, OutlinedHelperName); 1355 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 1356 return CGF.GenerateOpenMPCapturedStmtFunction(*CS); 1357 } 1358 1359 llvm::Value *CGOpenMPRuntime::emitParallelOutlinedFunction( 1360 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1361 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 1362 const CapturedStmt *CS = D.getCapturedStmt(OMPD_parallel); 1363 return emitParallelOrTeamsOutlinedFunction( 1364 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen); 1365 } 1366 1367 llvm::Value *CGOpenMPRuntime::emitTeamsOutlinedFunction( 1368 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1369 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 1370 const CapturedStmt *CS = D.getCapturedStmt(OMPD_teams); 1371 return emitParallelOrTeamsOutlinedFunction( 1372 CGM, D, CS, ThreadIDVar, InnermostKind, getOutlinedHelperName(), CodeGen); 1373 } 1374 1375 llvm::Value *CGOpenMPRuntime::emitTaskOutlinedFunction( 1376 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 1377 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 1378 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1379 bool Tied, unsigned &NumberOfParts) { 1380 auto &&UntiedCodeGen = [this, &D, TaskTVar](CodeGenFunction &CGF, 1381 PrePostActionTy &) { 1382 llvm::Value *ThreadID = getThreadID(CGF, D.getBeginLoc()); 1383 llvm::Value *UpLoc = emitUpdateLocation(CGF, D.getBeginLoc()); 1384 llvm::Value *TaskArgs[] = { 1385 UpLoc, ThreadID, 1386 CGF.EmitLoadOfPointerLValue(CGF.GetAddrOfLocalVar(TaskTVar), 1387 TaskTVar->getType()->castAs<PointerType>()) 1388 .getPointer()}; 1389 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), TaskArgs); 1390 }; 1391 CGOpenMPTaskOutlinedRegionInfo::UntiedTaskActionTy Action(Tied, PartIDVar, 1392 UntiedCodeGen); 1393 CodeGen.setAction(Action); 1394 assert(!ThreadIDVar->getType()->isPointerType() && 1395 "thread id variable must be of type kmp_int32 for tasks"); 1396 const OpenMPDirectiveKind Region = 1397 isOpenMPTaskLoopDirective(D.getDirectiveKind()) ? OMPD_taskloop 1398 : OMPD_task; 1399 const CapturedStmt *CS = D.getCapturedStmt(Region); 1400 const auto *TD = dyn_cast<OMPTaskDirective>(&D); 1401 CodeGenFunction CGF(CGM, true); 1402 CGOpenMPTaskOutlinedRegionInfo CGInfo(*CS, ThreadIDVar, CodeGen, 1403 InnermostKind, 1404 TD ? TD->hasCancel() : false, Action); 1405 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 1406 llvm::Value *Res = CGF.GenerateCapturedStmtFunction(*CS); 1407 if (!Tied) 1408 NumberOfParts = Action.getNumberOfParts(); 1409 return Res; 1410 } 1411 1412 static void buildStructValue(ConstantStructBuilder &Fields, CodeGenModule &CGM, 1413 const RecordDecl *RD, const CGRecordLayout &RL, 1414 ArrayRef<llvm::Constant *> Data) { 1415 llvm::StructType *StructTy = RL.getLLVMType(); 1416 unsigned PrevIdx = 0; 1417 ConstantInitBuilder CIBuilder(CGM); 1418 auto DI = Data.begin(); 1419 for (const FieldDecl *FD : RD->fields()) { 1420 unsigned Idx = RL.getLLVMFieldNo(FD); 1421 // Fill the alignment. 1422 for (unsigned I = PrevIdx; I < Idx; ++I) 1423 Fields.add(llvm::Constant::getNullValue(StructTy->getElementType(I))); 1424 PrevIdx = Idx + 1; 1425 Fields.add(*DI); 1426 ++DI; 1427 } 1428 } 1429 1430 template <class... As> 1431 static llvm::GlobalVariable * 1432 createGlobalStruct(CodeGenModule &CGM, QualType Ty, bool IsConstant, 1433 ArrayRef<llvm::Constant *> Data, const Twine &Name, 1434 As &&... Args) { 1435 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl()); 1436 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD); 1437 ConstantInitBuilder CIBuilder(CGM); 1438 ConstantStructBuilder Fields = CIBuilder.beginStruct(RL.getLLVMType()); 1439 buildStructValue(Fields, CGM, RD, RL, Data); 1440 return Fields.finishAndCreateGlobal( 1441 Name, CGM.getContext().getAlignOfGlobalVarInChars(Ty), IsConstant, 1442 std::forward<As>(Args)...); 1443 } 1444 1445 template <typename T> 1446 static void 1447 createConstantGlobalStructAndAddToParent(CodeGenModule &CGM, QualType Ty, 1448 ArrayRef<llvm::Constant *> Data, 1449 T &Parent) { 1450 const auto *RD = cast<RecordDecl>(Ty->getAsTagDecl()); 1451 const CGRecordLayout &RL = CGM.getTypes().getCGRecordLayout(RD); 1452 ConstantStructBuilder Fields = Parent.beginStruct(RL.getLLVMType()); 1453 buildStructValue(Fields, CGM, RD, RL, Data); 1454 Fields.finishAndAddTo(Parent); 1455 } 1456 1457 Address CGOpenMPRuntime::getOrCreateDefaultLocation(unsigned Flags) { 1458 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy); 1459 llvm::Value *Entry = OpenMPDefaultLocMap.lookup(Flags); 1460 if (!Entry) { 1461 if (!DefaultOpenMPPSource) { 1462 // Initialize default location for psource field of ident_t structure of 1463 // all ident_t objects. Format is ";file;function;line;column;;". 1464 // Taken from 1465 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp_str.c 1466 DefaultOpenMPPSource = 1467 CGM.GetAddrOfConstantCString(";unknown;unknown;0;0;;").getPointer(); 1468 DefaultOpenMPPSource = 1469 llvm::ConstantExpr::getBitCast(DefaultOpenMPPSource, CGM.Int8PtrTy); 1470 } 1471 1472 llvm::Constant *Data[] = {llvm::ConstantInt::getNullValue(CGM.Int32Ty), 1473 llvm::ConstantInt::get(CGM.Int32Ty, Flags), 1474 llvm::ConstantInt::getNullValue(CGM.Int32Ty), 1475 llvm::ConstantInt::getNullValue(CGM.Int32Ty), 1476 DefaultOpenMPPSource}; 1477 llvm::GlobalValue *DefaultOpenMPLocation = 1478 createGlobalStruct(CGM, IdentQTy, /*IsConstant=*/false, Data, "", 1479 llvm::GlobalValue::PrivateLinkage); 1480 DefaultOpenMPLocation->setUnnamedAddr( 1481 llvm::GlobalValue::UnnamedAddr::Global); 1482 1483 OpenMPDefaultLocMap[Flags] = Entry = DefaultOpenMPLocation; 1484 } 1485 return Address(Entry, Align); 1486 } 1487 1488 llvm::Value *CGOpenMPRuntime::emitUpdateLocation(CodeGenFunction &CGF, 1489 SourceLocation Loc, 1490 unsigned Flags) { 1491 Flags |= OMP_IDENT_KMPC; 1492 // If no debug info is generated - return global default location. 1493 if (CGM.getCodeGenOpts().getDebugInfo() == codegenoptions::NoDebugInfo || 1494 Loc.isInvalid()) 1495 return getOrCreateDefaultLocation(Flags).getPointer(); 1496 1497 assert(CGF.CurFn && "No function in current CodeGenFunction."); 1498 1499 CharUnits Align = CGM.getContext().getTypeAlignInChars(IdentQTy); 1500 Address LocValue = Address::invalid(); 1501 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn); 1502 if (I != OpenMPLocThreadIDMap.end()) 1503 LocValue = Address(I->second.DebugLoc, Align); 1504 1505 // OpenMPLocThreadIDMap may have null DebugLoc and non-null ThreadID, if 1506 // GetOpenMPThreadID was called before this routine. 1507 if (!LocValue.isValid()) { 1508 // Generate "ident_t .kmpc_loc.addr;" 1509 Address AI = CGF.CreateMemTemp(IdentQTy, ".kmpc_loc.addr"); 1510 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1511 Elem.second.DebugLoc = AI.getPointer(); 1512 LocValue = AI; 1513 1514 CGBuilderTy::InsertPointGuard IPG(CGF.Builder); 1515 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt); 1516 CGF.Builder.CreateMemCpy(LocValue, getOrCreateDefaultLocation(Flags), 1517 CGF.getTypeSize(IdentQTy)); 1518 } 1519 1520 // char **psource = &.kmpc_loc_<flags>.addr.psource; 1521 LValue Base = CGF.MakeAddrLValue(LocValue, IdentQTy); 1522 auto Fields = cast<RecordDecl>(IdentQTy->getAsTagDecl())->field_begin(); 1523 LValue PSource = 1524 CGF.EmitLValueForField(Base, *std::next(Fields, IdentField_PSource)); 1525 1526 llvm::Value *OMPDebugLoc = OpenMPDebugLocMap.lookup(Loc.getRawEncoding()); 1527 if (OMPDebugLoc == nullptr) { 1528 SmallString<128> Buffer2; 1529 llvm::raw_svector_ostream OS2(Buffer2); 1530 // Build debug location 1531 PresumedLoc PLoc = CGF.getContext().getSourceManager().getPresumedLoc(Loc); 1532 OS2 << ";" << PLoc.getFilename() << ";"; 1533 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CGF.CurFuncDecl)) 1534 OS2 << FD->getQualifiedNameAsString(); 1535 OS2 << ";" << PLoc.getLine() << ";" << PLoc.getColumn() << ";;"; 1536 OMPDebugLoc = CGF.Builder.CreateGlobalStringPtr(OS2.str()); 1537 OpenMPDebugLocMap[Loc.getRawEncoding()] = OMPDebugLoc; 1538 } 1539 // *psource = ";<File>;<Function>;<Line>;<Column>;;"; 1540 CGF.EmitStoreOfScalar(OMPDebugLoc, PSource); 1541 1542 // Our callers always pass this to a runtime function, so for 1543 // convenience, go ahead and return a naked pointer. 1544 return LocValue.getPointer(); 1545 } 1546 1547 llvm::Value *CGOpenMPRuntime::getThreadID(CodeGenFunction &CGF, 1548 SourceLocation Loc) { 1549 assert(CGF.CurFn && "No function in current CodeGenFunction."); 1550 1551 llvm::Value *ThreadID = nullptr; 1552 // Check whether we've already cached a load of the thread id in this 1553 // function. 1554 auto I = OpenMPLocThreadIDMap.find(CGF.CurFn); 1555 if (I != OpenMPLocThreadIDMap.end()) { 1556 ThreadID = I->second.ThreadID; 1557 if (ThreadID != nullptr) 1558 return ThreadID; 1559 } 1560 // If exceptions are enabled, do not use parameter to avoid possible crash. 1561 if (!CGF.EHStack.requiresLandingPad() || !CGF.getLangOpts().Exceptions || 1562 !CGF.getLangOpts().CXXExceptions || 1563 CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) { 1564 if (auto *OMPRegionInfo = 1565 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 1566 if (OMPRegionInfo->getThreadIDVariable()) { 1567 // Check if this an outlined function with thread id passed as argument. 1568 LValue LVal = OMPRegionInfo->getThreadIDVariableLValue(CGF); 1569 ThreadID = CGF.EmitLoadOfScalar(LVal, Loc); 1570 // If value loaded in entry block, cache it and use it everywhere in 1571 // function. 1572 if (CGF.Builder.GetInsertBlock() == CGF.AllocaInsertPt->getParent()) { 1573 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1574 Elem.second.ThreadID = ThreadID; 1575 } 1576 return ThreadID; 1577 } 1578 } 1579 } 1580 1581 // This is not an outlined function region - need to call __kmpc_int32 1582 // kmpc_global_thread_num(ident_t *loc). 1583 // Generate thread id value and cache this value for use across the 1584 // function. 1585 CGBuilderTy::InsertPointGuard IPG(CGF.Builder); 1586 CGF.Builder.SetInsertPoint(CGF.AllocaInsertPt); 1587 llvm::CallInst *Call = CGF.Builder.CreateCall( 1588 createRuntimeFunction(OMPRTL__kmpc_global_thread_num), 1589 emitUpdateLocation(CGF, Loc)); 1590 Call->setCallingConv(CGF.getRuntimeCC()); 1591 auto &Elem = OpenMPLocThreadIDMap.FindAndConstruct(CGF.CurFn); 1592 Elem.second.ThreadID = Call; 1593 return Call; 1594 } 1595 1596 void CGOpenMPRuntime::functionFinished(CodeGenFunction &CGF) { 1597 assert(CGF.CurFn && "No function in current CodeGenFunction."); 1598 if (OpenMPLocThreadIDMap.count(CGF.CurFn)) 1599 OpenMPLocThreadIDMap.erase(CGF.CurFn); 1600 if (FunctionUDRMap.count(CGF.CurFn) > 0) { 1601 for(auto *D : FunctionUDRMap[CGF.CurFn]) 1602 UDRMap.erase(D); 1603 FunctionUDRMap.erase(CGF.CurFn); 1604 } 1605 } 1606 1607 llvm::Type *CGOpenMPRuntime::getIdentTyPointerTy() { 1608 return IdentTy->getPointerTo(); 1609 } 1610 1611 llvm::Type *CGOpenMPRuntime::getKmpc_MicroPointerTy() { 1612 if (!Kmpc_MicroTy) { 1613 // Build void (*kmpc_micro)(kmp_int32 *global_tid, kmp_int32 *bound_tid,...) 1614 llvm::Type *MicroParams[] = {llvm::PointerType::getUnqual(CGM.Int32Ty), 1615 llvm::PointerType::getUnqual(CGM.Int32Ty)}; 1616 Kmpc_MicroTy = llvm::FunctionType::get(CGM.VoidTy, MicroParams, true); 1617 } 1618 return llvm::PointerType::getUnqual(Kmpc_MicroTy); 1619 } 1620 1621 llvm::Constant * 1622 CGOpenMPRuntime::createRuntimeFunction(unsigned Function) { 1623 llvm::Constant *RTLFn = nullptr; 1624 switch (static_cast<OpenMPRTLFunction>(Function)) { 1625 case OMPRTL__kmpc_fork_call: { 1626 // Build void __kmpc_fork_call(ident_t *loc, kmp_int32 argc, kmpc_micro 1627 // microtask, ...); 1628 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1629 getKmpc_MicroPointerTy()}; 1630 auto *FnTy = 1631 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true); 1632 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_call"); 1633 break; 1634 } 1635 case OMPRTL__kmpc_global_thread_num: { 1636 // Build kmp_int32 __kmpc_global_thread_num(ident_t *loc); 1637 llvm::Type *TypeParams[] = {getIdentTyPointerTy()}; 1638 auto *FnTy = 1639 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 1640 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_global_thread_num"); 1641 break; 1642 } 1643 case OMPRTL__kmpc_threadprivate_cached: { 1644 // Build void *__kmpc_threadprivate_cached(ident_t *loc, 1645 // kmp_int32 global_tid, void *data, size_t size, void ***cache); 1646 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1647 CGM.VoidPtrTy, CGM.SizeTy, 1648 CGM.VoidPtrTy->getPointerTo()->getPointerTo()}; 1649 auto *FnTy = 1650 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg*/ false); 1651 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_cached"); 1652 break; 1653 } 1654 case OMPRTL__kmpc_critical: { 1655 // Build void __kmpc_critical(ident_t *loc, kmp_int32 global_tid, 1656 // kmp_critical_name *crit); 1657 llvm::Type *TypeParams[] = { 1658 getIdentTyPointerTy(), CGM.Int32Ty, 1659 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1660 auto *FnTy = 1661 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1662 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical"); 1663 break; 1664 } 1665 case OMPRTL__kmpc_critical_with_hint: { 1666 // Build void __kmpc_critical_with_hint(ident_t *loc, kmp_int32 global_tid, 1667 // kmp_critical_name *crit, uintptr_t hint); 1668 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1669 llvm::PointerType::getUnqual(KmpCriticalNameTy), 1670 CGM.IntPtrTy}; 1671 auto *FnTy = 1672 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1673 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_critical_with_hint"); 1674 break; 1675 } 1676 case OMPRTL__kmpc_threadprivate_register: { 1677 // Build void __kmpc_threadprivate_register(ident_t *, void *data, 1678 // kmpc_ctor ctor, kmpc_cctor cctor, kmpc_dtor dtor); 1679 // typedef void *(*kmpc_ctor)(void *); 1680 auto *KmpcCtorTy = 1681 llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy, 1682 /*isVarArg*/ false)->getPointerTo(); 1683 // typedef void *(*kmpc_cctor)(void *, void *); 1684 llvm::Type *KmpcCopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1685 auto *KmpcCopyCtorTy = 1686 llvm::FunctionType::get(CGM.VoidPtrTy, KmpcCopyCtorTyArgs, 1687 /*isVarArg*/ false) 1688 ->getPointerTo(); 1689 // typedef void (*kmpc_dtor)(void *); 1690 auto *KmpcDtorTy = 1691 llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, /*isVarArg*/ false) 1692 ->getPointerTo(); 1693 llvm::Type *FnTyArgs[] = {getIdentTyPointerTy(), CGM.VoidPtrTy, KmpcCtorTy, 1694 KmpcCopyCtorTy, KmpcDtorTy}; 1695 auto *FnTy = llvm::FunctionType::get(CGM.VoidTy, FnTyArgs, 1696 /*isVarArg*/ false); 1697 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_threadprivate_register"); 1698 break; 1699 } 1700 case OMPRTL__kmpc_end_critical: { 1701 // Build void __kmpc_end_critical(ident_t *loc, kmp_int32 global_tid, 1702 // kmp_critical_name *crit); 1703 llvm::Type *TypeParams[] = { 1704 getIdentTyPointerTy(), CGM.Int32Ty, 1705 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1706 auto *FnTy = 1707 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1708 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_critical"); 1709 break; 1710 } 1711 case OMPRTL__kmpc_cancel_barrier: { 1712 // Build kmp_int32 __kmpc_cancel_barrier(ident_t *loc, kmp_int32 1713 // global_tid); 1714 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1715 auto *FnTy = 1716 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 1717 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_cancel_barrier"); 1718 break; 1719 } 1720 case OMPRTL__kmpc_barrier: { 1721 // Build void __kmpc_barrier(ident_t *loc, kmp_int32 global_tid); 1722 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1723 auto *FnTy = 1724 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1725 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name*/ "__kmpc_barrier"); 1726 break; 1727 } 1728 case OMPRTL__kmpc_for_static_fini: { 1729 // Build void __kmpc_for_static_fini(ident_t *loc, kmp_int32 global_tid); 1730 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1731 auto *FnTy = 1732 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1733 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_for_static_fini"); 1734 break; 1735 } 1736 case OMPRTL__kmpc_push_num_threads: { 1737 // Build void __kmpc_push_num_threads(ident_t *loc, kmp_int32 global_tid, 1738 // kmp_int32 num_threads) 1739 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1740 CGM.Int32Ty}; 1741 auto *FnTy = 1742 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1743 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_threads"); 1744 break; 1745 } 1746 case OMPRTL__kmpc_serialized_parallel: { 1747 // Build void __kmpc_serialized_parallel(ident_t *loc, kmp_int32 1748 // global_tid); 1749 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1750 auto *FnTy = 1751 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1752 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_serialized_parallel"); 1753 break; 1754 } 1755 case OMPRTL__kmpc_end_serialized_parallel: { 1756 // Build void __kmpc_end_serialized_parallel(ident_t *loc, kmp_int32 1757 // global_tid); 1758 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1759 auto *FnTy = 1760 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1761 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_serialized_parallel"); 1762 break; 1763 } 1764 case OMPRTL__kmpc_flush: { 1765 // Build void __kmpc_flush(ident_t *loc); 1766 llvm::Type *TypeParams[] = {getIdentTyPointerTy()}; 1767 auto *FnTy = 1768 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1769 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_flush"); 1770 break; 1771 } 1772 case OMPRTL__kmpc_master: { 1773 // Build kmp_int32 __kmpc_master(ident_t *loc, kmp_int32 global_tid); 1774 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1775 auto *FnTy = 1776 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1777 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_master"); 1778 break; 1779 } 1780 case OMPRTL__kmpc_end_master: { 1781 // Build void __kmpc_end_master(ident_t *loc, kmp_int32 global_tid); 1782 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1783 auto *FnTy = 1784 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1785 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_master"); 1786 break; 1787 } 1788 case OMPRTL__kmpc_omp_taskyield: { 1789 // Build kmp_int32 __kmpc_omp_taskyield(ident_t *, kmp_int32 global_tid, 1790 // int end_part); 1791 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 1792 auto *FnTy = 1793 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1794 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_taskyield"); 1795 break; 1796 } 1797 case OMPRTL__kmpc_single: { 1798 // Build kmp_int32 __kmpc_single(ident_t *loc, kmp_int32 global_tid); 1799 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1800 auto *FnTy = 1801 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1802 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_single"); 1803 break; 1804 } 1805 case OMPRTL__kmpc_end_single: { 1806 // Build void __kmpc_end_single(ident_t *loc, kmp_int32 global_tid); 1807 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1808 auto *FnTy = 1809 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1810 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_single"); 1811 break; 1812 } 1813 case OMPRTL__kmpc_omp_task_alloc: { 1814 // Build kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, 1815 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 1816 // kmp_routine_entry_t *task_entry); 1817 assert(KmpRoutineEntryPtrTy != nullptr && 1818 "Type kmp_routine_entry_t must be created."); 1819 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, 1820 CGM.SizeTy, CGM.SizeTy, KmpRoutineEntryPtrTy}; 1821 // Return void * and then cast to particular kmp_task_t type. 1822 auto *FnTy = 1823 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false); 1824 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_alloc"); 1825 break; 1826 } 1827 case OMPRTL__kmpc_omp_task: { 1828 // Build kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t 1829 // *new_task); 1830 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1831 CGM.VoidPtrTy}; 1832 auto *FnTy = 1833 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1834 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task"); 1835 break; 1836 } 1837 case OMPRTL__kmpc_copyprivate: { 1838 // Build void __kmpc_copyprivate(ident_t *loc, kmp_int32 global_tid, 1839 // size_t cpy_size, void *cpy_data, void(*cpy_func)(void *, void *), 1840 // kmp_int32 didit); 1841 llvm::Type *CpyTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1842 auto *CpyFnTy = 1843 llvm::FunctionType::get(CGM.VoidTy, CpyTypeParams, /*isVarArg=*/false); 1844 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.SizeTy, 1845 CGM.VoidPtrTy, CpyFnTy->getPointerTo(), 1846 CGM.Int32Ty}; 1847 auto *FnTy = 1848 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1849 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_copyprivate"); 1850 break; 1851 } 1852 case OMPRTL__kmpc_reduce: { 1853 // Build kmp_int32 __kmpc_reduce(ident_t *loc, kmp_int32 global_tid, 1854 // kmp_int32 num_vars, size_t reduce_size, void *reduce_data, void 1855 // (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name *lck); 1856 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1857 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams, 1858 /*isVarArg=*/false); 1859 llvm::Type *TypeParams[] = { 1860 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy, 1861 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(), 1862 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1863 auto *FnTy = 1864 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1865 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce"); 1866 break; 1867 } 1868 case OMPRTL__kmpc_reduce_nowait: { 1869 // Build kmp_int32 __kmpc_reduce_nowait(ident_t *loc, kmp_int32 1870 // global_tid, kmp_int32 num_vars, size_t reduce_size, void *reduce_data, 1871 // void (*reduce_func)(void *lhs_data, void *rhs_data), kmp_critical_name 1872 // *lck); 1873 llvm::Type *ReduceTypeParams[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 1874 auto *ReduceFnTy = llvm::FunctionType::get(CGM.VoidTy, ReduceTypeParams, 1875 /*isVarArg=*/false); 1876 llvm::Type *TypeParams[] = { 1877 getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, CGM.SizeTy, 1878 CGM.VoidPtrTy, ReduceFnTy->getPointerTo(), 1879 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1880 auto *FnTy = 1881 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1882 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_reduce_nowait"); 1883 break; 1884 } 1885 case OMPRTL__kmpc_end_reduce: { 1886 // Build void __kmpc_end_reduce(ident_t *loc, kmp_int32 global_tid, 1887 // kmp_critical_name *lck); 1888 llvm::Type *TypeParams[] = { 1889 getIdentTyPointerTy(), CGM.Int32Ty, 1890 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1891 auto *FnTy = 1892 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1893 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce"); 1894 break; 1895 } 1896 case OMPRTL__kmpc_end_reduce_nowait: { 1897 // Build __kmpc_end_reduce_nowait(ident_t *loc, kmp_int32 global_tid, 1898 // kmp_critical_name *lck); 1899 llvm::Type *TypeParams[] = { 1900 getIdentTyPointerTy(), CGM.Int32Ty, 1901 llvm::PointerType::getUnqual(KmpCriticalNameTy)}; 1902 auto *FnTy = 1903 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1904 RTLFn = 1905 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_end_reduce_nowait"); 1906 break; 1907 } 1908 case OMPRTL__kmpc_omp_task_begin_if0: { 1909 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t 1910 // *new_task); 1911 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1912 CGM.VoidPtrTy}; 1913 auto *FnTy = 1914 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1915 RTLFn = 1916 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_begin_if0"); 1917 break; 1918 } 1919 case OMPRTL__kmpc_omp_task_complete_if0: { 1920 // Build void __kmpc_omp_task(ident_t *, kmp_int32 gtid, kmp_task_t 1921 // *new_task); 1922 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1923 CGM.VoidPtrTy}; 1924 auto *FnTy = 1925 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1926 RTLFn = CGM.CreateRuntimeFunction(FnTy, 1927 /*Name=*/"__kmpc_omp_task_complete_if0"); 1928 break; 1929 } 1930 case OMPRTL__kmpc_ordered: { 1931 // Build void __kmpc_ordered(ident_t *loc, kmp_int32 global_tid); 1932 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1933 auto *FnTy = 1934 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1935 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_ordered"); 1936 break; 1937 } 1938 case OMPRTL__kmpc_end_ordered: { 1939 // Build void __kmpc_end_ordered(ident_t *loc, kmp_int32 global_tid); 1940 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1941 auto *FnTy = 1942 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1943 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_ordered"); 1944 break; 1945 } 1946 case OMPRTL__kmpc_omp_taskwait: { 1947 // Build kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 global_tid); 1948 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1949 auto *FnTy = 1950 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1951 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_omp_taskwait"); 1952 break; 1953 } 1954 case OMPRTL__kmpc_taskgroup: { 1955 // Build void __kmpc_taskgroup(ident_t *loc, kmp_int32 global_tid); 1956 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1957 auto *FnTy = 1958 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1959 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_taskgroup"); 1960 break; 1961 } 1962 case OMPRTL__kmpc_end_taskgroup: { 1963 // Build void __kmpc_end_taskgroup(ident_t *loc, kmp_int32 global_tid); 1964 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 1965 auto *FnTy = 1966 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 1967 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_end_taskgroup"); 1968 break; 1969 } 1970 case OMPRTL__kmpc_push_proc_bind: { 1971 // Build void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 global_tid, 1972 // int proc_bind) 1973 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 1974 auto *FnTy = 1975 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 1976 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_proc_bind"); 1977 break; 1978 } 1979 case OMPRTL__kmpc_omp_task_with_deps: { 1980 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid, 1981 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list, 1982 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list); 1983 llvm::Type *TypeParams[] = { 1984 getIdentTyPointerTy(), CGM.Int32Ty, CGM.VoidPtrTy, CGM.Int32Ty, 1985 CGM.VoidPtrTy, CGM.Int32Ty, CGM.VoidPtrTy}; 1986 auto *FnTy = 1987 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg=*/false); 1988 RTLFn = 1989 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_task_with_deps"); 1990 break; 1991 } 1992 case OMPRTL__kmpc_omp_wait_deps: { 1993 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid, 1994 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 ndeps_noalias, 1995 // kmp_depend_info_t *noalias_dep_list); 1996 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 1997 CGM.Int32Ty, CGM.VoidPtrTy, 1998 CGM.Int32Ty, CGM.VoidPtrTy}; 1999 auto *FnTy = 2000 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2001 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_omp_wait_deps"); 2002 break; 2003 } 2004 case OMPRTL__kmpc_cancellationpoint: { 2005 // Build kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32 2006 // global_tid, kmp_int32 cncl_kind) 2007 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 2008 auto *FnTy = 2009 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2010 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancellationpoint"); 2011 break; 2012 } 2013 case OMPRTL__kmpc_cancel: { 2014 // Build kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid, 2015 // kmp_int32 cncl_kind) 2016 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.IntTy}; 2017 auto *FnTy = 2018 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2019 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_cancel"); 2020 break; 2021 } 2022 case OMPRTL__kmpc_push_num_teams: { 2023 // Build void kmpc_push_num_teams (ident_t loc, kmp_int32 global_tid, 2024 // kmp_int32 num_teams, kmp_int32 num_threads) 2025 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, CGM.Int32Ty, 2026 CGM.Int32Ty}; 2027 auto *FnTy = 2028 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2029 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_push_num_teams"); 2030 break; 2031 } 2032 case OMPRTL__kmpc_fork_teams: { 2033 // Build void __kmpc_fork_teams(ident_t *loc, kmp_int32 argc, kmpc_micro 2034 // microtask, ...); 2035 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 2036 getKmpc_MicroPointerTy()}; 2037 auto *FnTy = 2038 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ true); 2039 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__kmpc_fork_teams"); 2040 break; 2041 } 2042 case OMPRTL__kmpc_taskloop: { 2043 // Build void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int 2044 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int 2045 // sched, kmp_uint64 grainsize, void *task_dup); 2046 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), 2047 CGM.IntTy, 2048 CGM.VoidPtrTy, 2049 CGM.IntTy, 2050 CGM.Int64Ty->getPointerTo(), 2051 CGM.Int64Ty->getPointerTo(), 2052 CGM.Int64Ty, 2053 CGM.IntTy, 2054 CGM.IntTy, 2055 CGM.Int64Ty, 2056 CGM.VoidPtrTy}; 2057 auto *FnTy = 2058 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2059 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_taskloop"); 2060 break; 2061 } 2062 case OMPRTL__kmpc_doacross_init: { 2063 // Build void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, kmp_int32 2064 // num_dims, struct kmp_dim *dims); 2065 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), 2066 CGM.Int32Ty, 2067 CGM.Int32Ty, 2068 CGM.VoidPtrTy}; 2069 auto *FnTy = 2070 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2071 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_init"); 2072 break; 2073 } 2074 case OMPRTL__kmpc_doacross_fini: { 2075 // Build void __kmpc_doacross_fini(ident_t *loc, kmp_int32 gtid); 2076 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty}; 2077 auto *FnTy = 2078 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2079 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_fini"); 2080 break; 2081 } 2082 case OMPRTL__kmpc_doacross_post: { 2083 // Build void __kmpc_doacross_post(ident_t *loc, kmp_int32 gtid, kmp_int64 2084 // *vec); 2085 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 2086 CGM.Int64Ty->getPointerTo()}; 2087 auto *FnTy = 2088 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2089 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_post"); 2090 break; 2091 } 2092 case OMPRTL__kmpc_doacross_wait: { 2093 // Build void __kmpc_doacross_wait(ident_t *loc, kmp_int32 gtid, kmp_int64 2094 // *vec); 2095 llvm::Type *TypeParams[] = {getIdentTyPointerTy(), CGM.Int32Ty, 2096 CGM.Int64Ty->getPointerTo()}; 2097 auto *FnTy = 2098 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2099 RTLFn = CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_doacross_wait"); 2100 break; 2101 } 2102 case OMPRTL__kmpc_task_reduction_init: { 2103 // Build void *__kmpc_task_reduction_init(int gtid, int num_data, void 2104 // *data); 2105 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.IntTy, CGM.VoidPtrTy}; 2106 auto *FnTy = 2107 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false); 2108 RTLFn = 2109 CGM.CreateRuntimeFunction(FnTy, /*Name=*/"__kmpc_task_reduction_init"); 2110 break; 2111 } 2112 case OMPRTL__kmpc_task_reduction_get_th_data: { 2113 // Build void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void 2114 // *d); 2115 llvm::Type *TypeParams[] = {CGM.IntTy, CGM.VoidPtrTy, CGM.VoidPtrTy}; 2116 auto *FnTy = 2117 llvm::FunctionType::get(CGM.VoidPtrTy, TypeParams, /*isVarArg=*/false); 2118 RTLFn = CGM.CreateRuntimeFunction( 2119 FnTy, /*Name=*/"__kmpc_task_reduction_get_th_data"); 2120 break; 2121 } 2122 case OMPRTL__tgt_target: { 2123 // Build int32_t __tgt_target(int64_t device_id, void *host_ptr, int32_t 2124 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2125 // *arg_types); 2126 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2127 CGM.VoidPtrTy, 2128 CGM.Int32Ty, 2129 CGM.VoidPtrPtrTy, 2130 CGM.VoidPtrPtrTy, 2131 CGM.SizeTy->getPointerTo(), 2132 CGM.Int64Ty->getPointerTo()}; 2133 auto *FnTy = 2134 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2135 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target"); 2136 break; 2137 } 2138 case OMPRTL__tgt_target_nowait: { 2139 // Build int32_t __tgt_target_nowait(int64_t device_id, void *host_ptr, 2140 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, 2141 // int64_t *arg_types); 2142 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2143 CGM.VoidPtrTy, 2144 CGM.Int32Ty, 2145 CGM.VoidPtrPtrTy, 2146 CGM.VoidPtrPtrTy, 2147 CGM.SizeTy->getPointerTo(), 2148 CGM.Int64Ty->getPointerTo()}; 2149 auto *FnTy = 2150 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2151 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_nowait"); 2152 break; 2153 } 2154 case OMPRTL__tgt_target_teams: { 2155 // Build int32_t __tgt_target_teams(int64_t device_id, void *host_ptr, 2156 // int32_t arg_num, void** args_base, void **args, size_t *arg_sizes, 2157 // int64_t *arg_types, int32_t num_teams, int32_t thread_limit); 2158 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2159 CGM.VoidPtrTy, 2160 CGM.Int32Ty, 2161 CGM.VoidPtrPtrTy, 2162 CGM.VoidPtrPtrTy, 2163 CGM.SizeTy->getPointerTo(), 2164 CGM.Int64Ty->getPointerTo(), 2165 CGM.Int32Ty, 2166 CGM.Int32Ty}; 2167 auto *FnTy = 2168 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2169 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams"); 2170 break; 2171 } 2172 case OMPRTL__tgt_target_teams_nowait: { 2173 // Build int32_t __tgt_target_teams_nowait(int64_t device_id, void 2174 // *host_ptr, int32_t arg_num, void** args_base, void **args, size_t 2175 // *arg_sizes, int64_t *arg_types, int32_t num_teams, int32_t thread_limit); 2176 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2177 CGM.VoidPtrTy, 2178 CGM.Int32Ty, 2179 CGM.VoidPtrPtrTy, 2180 CGM.VoidPtrPtrTy, 2181 CGM.SizeTy->getPointerTo(), 2182 CGM.Int64Ty->getPointerTo(), 2183 CGM.Int32Ty, 2184 CGM.Int32Ty}; 2185 auto *FnTy = 2186 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2187 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_teams_nowait"); 2188 break; 2189 } 2190 case OMPRTL__tgt_register_lib: { 2191 // Build void __tgt_register_lib(__tgt_bin_desc *desc); 2192 QualType ParamTy = 2193 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy()); 2194 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)}; 2195 auto *FnTy = 2196 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2197 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_register_lib"); 2198 break; 2199 } 2200 case OMPRTL__tgt_unregister_lib: { 2201 // Build void __tgt_unregister_lib(__tgt_bin_desc *desc); 2202 QualType ParamTy = 2203 CGM.getContext().getPointerType(getTgtBinaryDescriptorQTy()); 2204 llvm::Type *TypeParams[] = {CGM.getTypes().ConvertTypeForMem(ParamTy)}; 2205 auto *FnTy = 2206 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2207 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_unregister_lib"); 2208 break; 2209 } 2210 case OMPRTL__tgt_target_data_begin: { 2211 // Build void __tgt_target_data_begin(int64_t device_id, int32_t arg_num, 2212 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 2213 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2214 CGM.Int32Ty, 2215 CGM.VoidPtrPtrTy, 2216 CGM.VoidPtrPtrTy, 2217 CGM.SizeTy->getPointerTo(), 2218 CGM.Int64Ty->getPointerTo()}; 2219 auto *FnTy = 2220 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2221 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin"); 2222 break; 2223 } 2224 case OMPRTL__tgt_target_data_begin_nowait: { 2225 // Build void __tgt_target_data_begin_nowait(int64_t device_id, int32_t 2226 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2227 // *arg_types); 2228 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2229 CGM.Int32Ty, 2230 CGM.VoidPtrPtrTy, 2231 CGM.VoidPtrPtrTy, 2232 CGM.SizeTy->getPointerTo(), 2233 CGM.Int64Ty->getPointerTo()}; 2234 auto *FnTy = 2235 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2236 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_begin_nowait"); 2237 break; 2238 } 2239 case OMPRTL__tgt_target_data_end: { 2240 // Build void __tgt_target_data_end(int64_t device_id, int32_t arg_num, 2241 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 2242 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2243 CGM.Int32Ty, 2244 CGM.VoidPtrPtrTy, 2245 CGM.VoidPtrPtrTy, 2246 CGM.SizeTy->getPointerTo(), 2247 CGM.Int64Ty->getPointerTo()}; 2248 auto *FnTy = 2249 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2250 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end"); 2251 break; 2252 } 2253 case OMPRTL__tgt_target_data_end_nowait: { 2254 // Build void __tgt_target_data_end_nowait(int64_t device_id, int32_t 2255 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2256 // *arg_types); 2257 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2258 CGM.Int32Ty, 2259 CGM.VoidPtrPtrTy, 2260 CGM.VoidPtrPtrTy, 2261 CGM.SizeTy->getPointerTo(), 2262 CGM.Int64Ty->getPointerTo()}; 2263 auto *FnTy = 2264 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2265 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_end_nowait"); 2266 break; 2267 } 2268 case OMPRTL__tgt_target_data_update: { 2269 // Build void __tgt_target_data_update(int64_t device_id, int32_t arg_num, 2270 // void** args_base, void **args, size_t *arg_sizes, int64_t *arg_types); 2271 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2272 CGM.Int32Ty, 2273 CGM.VoidPtrPtrTy, 2274 CGM.VoidPtrPtrTy, 2275 CGM.SizeTy->getPointerTo(), 2276 CGM.Int64Ty->getPointerTo()}; 2277 auto *FnTy = 2278 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2279 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update"); 2280 break; 2281 } 2282 case OMPRTL__tgt_target_data_update_nowait: { 2283 // Build void __tgt_target_data_update_nowait(int64_t device_id, int32_t 2284 // arg_num, void** args_base, void **args, size_t *arg_sizes, int64_t 2285 // *arg_types); 2286 llvm::Type *TypeParams[] = {CGM.Int64Ty, 2287 CGM.Int32Ty, 2288 CGM.VoidPtrPtrTy, 2289 CGM.VoidPtrPtrTy, 2290 CGM.SizeTy->getPointerTo(), 2291 CGM.Int64Ty->getPointerTo()}; 2292 auto *FnTy = 2293 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2294 RTLFn = CGM.CreateRuntimeFunction(FnTy, "__tgt_target_data_update_nowait"); 2295 break; 2296 } 2297 } 2298 assert(RTLFn && "Unable to find OpenMP runtime function"); 2299 return RTLFn; 2300 } 2301 2302 llvm::Constant *CGOpenMPRuntime::createForStaticInitFunction(unsigned IVSize, 2303 bool IVSigned) { 2304 assert((IVSize == 32 || IVSize == 64) && 2305 "IV size is not compatible with the omp runtime"); 2306 StringRef Name = IVSize == 32 ? (IVSigned ? "__kmpc_for_static_init_4" 2307 : "__kmpc_for_static_init_4u") 2308 : (IVSigned ? "__kmpc_for_static_init_8" 2309 : "__kmpc_for_static_init_8u"); 2310 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; 2311 auto *PtrTy = llvm::PointerType::getUnqual(ITy); 2312 llvm::Type *TypeParams[] = { 2313 getIdentTyPointerTy(), // loc 2314 CGM.Int32Ty, // tid 2315 CGM.Int32Ty, // schedtype 2316 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter 2317 PtrTy, // p_lower 2318 PtrTy, // p_upper 2319 PtrTy, // p_stride 2320 ITy, // incr 2321 ITy // chunk 2322 }; 2323 auto *FnTy = 2324 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2325 return CGM.CreateRuntimeFunction(FnTy, Name); 2326 } 2327 2328 llvm::Constant *CGOpenMPRuntime::createDispatchInitFunction(unsigned IVSize, 2329 bool IVSigned) { 2330 assert((IVSize == 32 || IVSize == 64) && 2331 "IV size is not compatible with the omp runtime"); 2332 StringRef Name = 2333 IVSize == 32 2334 ? (IVSigned ? "__kmpc_dispatch_init_4" : "__kmpc_dispatch_init_4u") 2335 : (IVSigned ? "__kmpc_dispatch_init_8" : "__kmpc_dispatch_init_8u"); 2336 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; 2337 llvm::Type *TypeParams[] = { getIdentTyPointerTy(), // loc 2338 CGM.Int32Ty, // tid 2339 CGM.Int32Ty, // schedtype 2340 ITy, // lower 2341 ITy, // upper 2342 ITy, // stride 2343 ITy // chunk 2344 }; 2345 auto *FnTy = 2346 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg*/ false); 2347 return CGM.CreateRuntimeFunction(FnTy, Name); 2348 } 2349 2350 llvm::Constant *CGOpenMPRuntime::createDispatchFiniFunction(unsigned IVSize, 2351 bool IVSigned) { 2352 assert((IVSize == 32 || IVSize == 64) && 2353 "IV size is not compatible with the omp runtime"); 2354 StringRef Name = 2355 IVSize == 32 2356 ? (IVSigned ? "__kmpc_dispatch_fini_4" : "__kmpc_dispatch_fini_4u") 2357 : (IVSigned ? "__kmpc_dispatch_fini_8" : "__kmpc_dispatch_fini_8u"); 2358 llvm::Type *TypeParams[] = { 2359 getIdentTyPointerTy(), // loc 2360 CGM.Int32Ty, // tid 2361 }; 2362 auto *FnTy = 2363 llvm::FunctionType::get(CGM.VoidTy, TypeParams, /*isVarArg=*/false); 2364 return CGM.CreateRuntimeFunction(FnTy, Name); 2365 } 2366 2367 llvm::Constant *CGOpenMPRuntime::createDispatchNextFunction(unsigned IVSize, 2368 bool IVSigned) { 2369 assert((IVSize == 32 || IVSize == 64) && 2370 "IV size is not compatible with the omp runtime"); 2371 StringRef Name = 2372 IVSize == 32 2373 ? (IVSigned ? "__kmpc_dispatch_next_4" : "__kmpc_dispatch_next_4u") 2374 : (IVSigned ? "__kmpc_dispatch_next_8" : "__kmpc_dispatch_next_8u"); 2375 llvm::Type *ITy = IVSize == 32 ? CGM.Int32Ty : CGM.Int64Ty; 2376 auto *PtrTy = llvm::PointerType::getUnqual(ITy); 2377 llvm::Type *TypeParams[] = { 2378 getIdentTyPointerTy(), // loc 2379 CGM.Int32Ty, // tid 2380 llvm::PointerType::getUnqual(CGM.Int32Ty), // p_lastiter 2381 PtrTy, // p_lower 2382 PtrTy, // p_upper 2383 PtrTy // p_stride 2384 }; 2385 auto *FnTy = 2386 llvm::FunctionType::get(CGM.Int32Ty, TypeParams, /*isVarArg*/ false); 2387 return CGM.CreateRuntimeFunction(FnTy, Name); 2388 } 2389 2390 Address CGOpenMPRuntime::getAddrOfDeclareTargetLink(const VarDecl *VD) { 2391 if (CGM.getLangOpts().OpenMPSimd) 2392 return Address::invalid(); 2393 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2394 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2395 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 2396 SmallString<64> PtrName; 2397 { 2398 llvm::raw_svector_ostream OS(PtrName); 2399 OS << CGM.getMangledName(GlobalDecl(VD)) << "_decl_tgt_link_ptr"; 2400 } 2401 llvm::Value *Ptr = CGM.getModule().getNamedValue(PtrName); 2402 if (!Ptr) { 2403 QualType PtrTy = CGM.getContext().getPointerType(VD->getType()); 2404 Ptr = getOrCreateInternalVariable(CGM.getTypes().ConvertTypeForMem(PtrTy), 2405 PtrName); 2406 if (!CGM.getLangOpts().OpenMPIsDevice) { 2407 auto *GV = cast<llvm::GlobalVariable>(Ptr); 2408 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 2409 GV->setInitializer(CGM.GetAddrOfGlobal(VD)); 2410 } 2411 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ptr)); 2412 registerTargetGlobalVariable(VD, cast<llvm::Constant>(Ptr)); 2413 } 2414 return Address(Ptr, CGM.getContext().getDeclAlign(VD)); 2415 } 2416 return Address::invalid(); 2417 } 2418 2419 llvm::Constant * 2420 CGOpenMPRuntime::getOrCreateThreadPrivateCache(const VarDecl *VD) { 2421 assert(!CGM.getLangOpts().OpenMPUseTLS || 2422 !CGM.getContext().getTargetInfo().isTLSSupported()); 2423 // Lookup the entry, lazily creating it if necessary. 2424 std::string Suffix = getName({"cache", ""}); 2425 return getOrCreateInternalVariable( 2426 CGM.Int8PtrPtrTy, Twine(CGM.getMangledName(VD)).concat(Suffix)); 2427 } 2428 2429 Address CGOpenMPRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF, 2430 const VarDecl *VD, 2431 Address VDAddr, 2432 SourceLocation Loc) { 2433 if (CGM.getLangOpts().OpenMPUseTLS && 2434 CGM.getContext().getTargetInfo().isTLSSupported()) 2435 return VDAddr; 2436 2437 llvm::Type *VarTy = VDAddr.getElementType(); 2438 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 2439 CGF.Builder.CreatePointerCast(VDAddr.getPointer(), 2440 CGM.Int8PtrTy), 2441 CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)), 2442 getOrCreateThreadPrivateCache(VD)}; 2443 return Address(CGF.EmitRuntimeCall( 2444 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args), 2445 VDAddr.getAlignment()); 2446 } 2447 2448 void CGOpenMPRuntime::emitThreadPrivateVarInit( 2449 CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor, 2450 llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc) { 2451 // Call kmp_int32 __kmpc_global_thread_num(&loc) to init OpenMP runtime 2452 // library. 2453 llvm::Value *OMPLoc = emitUpdateLocation(CGF, Loc); 2454 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_global_thread_num), 2455 OMPLoc); 2456 // Call __kmpc_threadprivate_register(&loc, &var, ctor, cctor/*NULL*/, dtor) 2457 // to register constructor/destructor for variable. 2458 llvm::Value *Args[] = { 2459 OMPLoc, CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.VoidPtrTy), 2460 Ctor, CopyCtor, Dtor}; 2461 CGF.EmitRuntimeCall( 2462 createRuntimeFunction(OMPRTL__kmpc_threadprivate_register), Args); 2463 } 2464 2465 llvm::Function *CGOpenMPRuntime::emitThreadPrivateVarDefinition( 2466 const VarDecl *VD, Address VDAddr, SourceLocation Loc, 2467 bool PerformInit, CodeGenFunction *CGF) { 2468 if (CGM.getLangOpts().OpenMPUseTLS && 2469 CGM.getContext().getTargetInfo().isTLSSupported()) 2470 return nullptr; 2471 2472 VD = VD->getDefinition(CGM.getContext()); 2473 if (VD && ThreadPrivateWithDefinition.count(VD) == 0) { 2474 ThreadPrivateWithDefinition.insert(VD); 2475 QualType ASTTy = VD->getType(); 2476 2477 llvm::Value *Ctor = nullptr, *CopyCtor = nullptr, *Dtor = nullptr; 2478 const Expr *Init = VD->getAnyInitializer(); 2479 if (CGM.getLangOpts().CPlusPlus && PerformInit) { 2480 // Generate function that re-emits the declaration's initializer into the 2481 // threadprivate copy of the variable VD 2482 CodeGenFunction CtorCGF(CGM); 2483 FunctionArgList Args; 2484 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, 2485 /*Id=*/nullptr, CGM.getContext().VoidPtrTy, 2486 ImplicitParamDecl::Other); 2487 Args.push_back(&Dst); 2488 2489 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( 2490 CGM.getContext().VoidPtrTy, Args); 2491 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2492 std::string Name = getName({"__kmpc_global_ctor_", ""}); 2493 llvm::Function *Fn = 2494 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc); 2495 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidPtrTy, Fn, FI, 2496 Args, Loc, Loc); 2497 llvm::Value *ArgVal = CtorCGF.EmitLoadOfScalar( 2498 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, 2499 CGM.getContext().VoidPtrTy, Dst.getLocation()); 2500 Address Arg = Address(ArgVal, VDAddr.getAlignment()); 2501 Arg = CtorCGF.Builder.CreateElementBitCast( 2502 Arg, CtorCGF.ConvertTypeForMem(ASTTy)); 2503 CtorCGF.EmitAnyExprToMem(Init, Arg, Init->getType().getQualifiers(), 2504 /*IsInitializer=*/true); 2505 ArgVal = CtorCGF.EmitLoadOfScalar( 2506 CtorCGF.GetAddrOfLocalVar(&Dst), /*Volatile=*/false, 2507 CGM.getContext().VoidPtrTy, Dst.getLocation()); 2508 CtorCGF.Builder.CreateStore(ArgVal, CtorCGF.ReturnValue); 2509 CtorCGF.FinishFunction(); 2510 Ctor = Fn; 2511 } 2512 if (VD->getType().isDestructedType() != QualType::DK_none) { 2513 // Generate function that emits destructor call for the threadprivate copy 2514 // of the variable VD 2515 CodeGenFunction DtorCGF(CGM); 2516 FunctionArgList Args; 2517 ImplicitParamDecl Dst(CGM.getContext(), /*DC=*/nullptr, Loc, 2518 /*Id=*/nullptr, CGM.getContext().VoidPtrTy, 2519 ImplicitParamDecl::Other); 2520 Args.push_back(&Dst); 2521 2522 const auto &FI = CGM.getTypes().arrangeBuiltinFunctionDeclaration( 2523 CGM.getContext().VoidTy, Args); 2524 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2525 std::string Name = getName({"__kmpc_global_dtor_", ""}); 2526 llvm::Function *Fn = 2527 CGM.CreateGlobalInitOrDestructFunction(FTy, Name, FI, Loc); 2528 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); 2529 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, Args, 2530 Loc, Loc); 2531 // Create a scope with an artificial location for the body of this function. 2532 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); 2533 llvm::Value *ArgVal = DtorCGF.EmitLoadOfScalar( 2534 DtorCGF.GetAddrOfLocalVar(&Dst), 2535 /*Volatile=*/false, CGM.getContext().VoidPtrTy, Dst.getLocation()); 2536 DtorCGF.emitDestroy(Address(ArgVal, VDAddr.getAlignment()), ASTTy, 2537 DtorCGF.getDestroyer(ASTTy.isDestructedType()), 2538 DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); 2539 DtorCGF.FinishFunction(); 2540 Dtor = Fn; 2541 } 2542 // Do not emit init function if it is not required. 2543 if (!Ctor && !Dtor) 2544 return nullptr; 2545 2546 llvm::Type *CopyCtorTyArgs[] = {CGM.VoidPtrTy, CGM.VoidPtrTy}; 2547 auto *CopyCtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CopyCtorTyArgs, 2548 /*isVarArg=*/false) 2549 ->getPointerTo(); 2550 // Copying constructor for the threadprivate variable. 2551 // Must be NULL - reserved by runtime, but currently it requires that this 2552 // parameter is always NULL. Otherwise it fires assertion. 2553 CopyCtor = llvm::Constant::getNullValue(CopyCtorTy); 2554 if (Ctor == nullptr) { 2555 auto *CtorTy = llvm::FunctionType::get(CGM.VoidPtrTy, CGM.VoidPtrTy, 2556 /*isVarArg=*/false) 2557 ->getPointerTo(); 2558 Ctor = llvm::Constant::getNullValue(CtorTy); 2559 } 2560 if (Dtor == nullptr) { 2561 auto *DtorTy = llvm::FunctionType::get(CGM.VoidTy, CGM.VoidPtrTy, 2562 /*isVarArg=*/false) 2563 ->getPointerTo(); 2564 Dtor = llvm::Constant::getNullValue(DtorTy); 2565 } 2566 if (!CGF) { 2567 auto *InitFunctionTy = 2568 llvm::FunctionType::get(CGM.VoidTy, /*isVarArg*/ false); 2569 std::string Name = getName({"__omp_threadprivate_init_", ""}); 2570 llvm::Function *InitFunction = CGM.CreateGlobalInitOrDestructFunction( 2571 InitFunctionTy, Name, CGM.getTypes().arrangeNullaryFunction()); 2572 CodeGenFunction InitCGF(CGM); 2573 FunctionArgList ArgList; 2574 InitCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, InitFunction, 2575 CGM.getTypes().arrangeNullaryFunction(), ArgList, 2576 Loc, Loc); 2577 emitThreadPrivateVarInit(InitCGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); 2578 InitCGF.FinishFunction(); 2579 return InitFunction; 2580 } 2581 emitThreadPrivateVarInit(*CGF, VDAddr, Ctor, CopyCtor, Dtor, Loc); 2582 } 2583 return nullptr; 2584 } 2585 2586 /// Obtain information that uniquely identifies a target entry. This 2587 /// consists of the file and device IDs as well as line number associated with 2588 /// the relevant entry source location. 2589 static void getTargetEntryUniqueInfo(ASTContext &C, SourceLocation Loc, 2590 unsigned &DeviceID, unsigned &FileID, 2591 unsigned &LineNum) { 2592 SourceManager &SM = C.getSourceManager(); 2593 2594 // The loc should be always valid and have a file ID (the user cannot use 2595 // #pragma directives in macros) 2596 2597 assert(Loc.isValid() && "Source location is expected to be always valid."); 2598 2599 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2600 assert(PLoc.isValid() && "Source location is expected to be always valid."); 2601 2602 llvm::sys::fs::UniqueID ID; 2603 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 2604 SM.getDiagnostics().Report(diag::err_cannot_open_file) 2605 << PLoc.getFilename() << EC.message(); 2606 2607 DeviceID = ID.getDevice(); 2608 FileID = ID.getFile(); 2609 LineNum = PLoc.getLine(); 2610 } 2611 2612 bool CGOpenMPRuntime::emitDeclareTargetVarDefinition(const VarDecl *VD, 2613 llvm::GlobalVariable *Addr, 2614 bool PerformInit) { 2615 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2616 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2617 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) 2618 return CGM.getLangOpts().OpenMPIsDevice; 2619 VD = VD->getDefinition(CGM.getContext()); 2620 if (VD && !DeclareTargetWithDefinition.insert(VD).second) 2621 return CGM.getLangOpts().OpenMPIsDevice; 2622 2623 QualType ASTTy = VD->getType(); 2624 2625 SourceLocation Loc = VD->getCanonicalDecl()->getBeginLoc(); 2626 // Produce the unique prefix to identify the new target regions. We use 2627 // the source location of the variable declaration which we know to not 2628 // conflict with any target region. 2629 unsigned DeviceID; 2630 unsigned FileID; 2631 unsigned Line; 2632 getTargetEntryUniqueInfo(CGM.getContext(), Loc, DeviceID, FileID, Line); 2633 SmallString<128> Buffer, Out; 2634 { 2635 llvm::raw_svector_ostream OS(Buffer); 2636 OS << "__omp_offloading_" << llvm::format("_%x", DeviceID) 2637 << llvm::format("_%x_", FileID) << VD->getName() << "_l" << Line; 2638 } 2639 2640 const Expr *Init = VD->getAnyInitializer(); 2641 if (CGM.getLangOpts().CPlusPlus && PerformInit) { 2642 llvm::Constant *Ctor; 2643 llvm::Constant *ID; 2644 if (CGM.getLangOpts().OpenMPIsDevice) { 2645 // Generate function that re-emits the declaration's initializer into 2646 // the threadprivate copy of the variable VD 2647 CodeGenFunction CtorCGF(CGM); 2648 2649 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2650 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2651 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction( 2652 FTy, Twine(Buffer, "_ctor"), FI, Loc); 2653 auto NL = ApplyDebugLocation::CreateEmpty(CtorCGF); 2654 CtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, 2655 FunctionArgList(), Loc, Loc); 2656 auto AL = ApplyDebugLocation::CreateArtificial(CtorCGF); 2657 CtorCGF.EmitAnyExprToMem(Init, 2658 Address(Addr, CGM.getContext().getDeclAlign(VD)), 2659 Init->getType().getQualifiers(), 2660 /*IsInitializer=*/true); 2661 CtorCGF.FinishFunction(); 2662 Ctor = Fn; 2663 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); 2664 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Ctor)); 2665 } else { 2666 Ctor = new llvm::GlobalVariable( 2667 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, 2668 llvm::GlobalValue::PrivateLinkage, 2669 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_ctor")); 2670 ID = Ctor; 2671 } 2672 2673 // Register the information for the entry associated with the constructor. 2674 Out.clear(); 2675 OffloadEntriesInfoManager.registerTargetRegionEntryInfo( 2676 DeviceID, FileID, Twine(Buffer, "_ctor").toStringRef(Out), Line, Ctor, 2677 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryCtor); 2678 } 2679 if (VD->getType().isDestructedType() != QualType::DK_none) { 2680 llvm::Constant *Dtor; 2681 llvm::Constant *ID; 2682 if (CGM.getLangOpts().OpenMPIsDevice) { 2683 // Generate function that emits destructor call for the threadprivate 2684 // copy of the variable VD 2685 CodeGenFunction DtorCGF(CGM); 2686 2687 const CGFunctionInfo &FI = CGM.getTypes().arrangeNullaryFunction(); 2688 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 2689 llvm::Function *Fn = CGM.CreateGlobalInitOrDestructFunction( 2690 FTy, Twine(Buffer, "_dtor"), FI, Loc); 2691 auto NL = ApplyDebugLocation::CreateEmpty(DtorCGF); 2692 DtorCGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, Fn, FI, 2693 FunctionArgList(), Loc, Loc); 2694 // Create a scope with an artificial location for the body of this 2695 // function. 2696 auto AL = ApplyDebugLocation::CreateArtificial(DtorCGF); 2697 DtorCGF.emitDestroy(Address(Addr, CGM.getContext().getDeclAlign(VD)), 2698 ASTTy, DtorCGF.getDestroyer(ASTTy.isDestructedType()), 2699 DtorCGF.needsEHCleanup(ASTTy.isDestructedType())); 2700 DtorCGF.FinishFunction(); 2701 Dtor = Fn; 2702 ID = llvm::ConstantExpr::getBitCast(Fn, CGM.Int8PtrTy); 2703 CGM.addUsedGlobal(cast<llvm::GlobalValue>(Dtor)); 2704 } else { 2705 Dtor = new llvm::GlobalVariable( 2706 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, 2707 llvm::GlobalValue::PrivateLinkage, 2708 llvm::Constant::getNullValue(CGM.Int8Ty), Twine(Buffer, "_dtor")); 2709 ID = Dtor; 2710 } 2711 // Register the information for the entry associated with the destructor. 2712 Out.clear(); 2713 OffloadEntriesInfoManager.registerTargetRegionEntryInfo( 2714 DeviceID, FileID, Twine(Buffer, "_dtor").toStringRef(Out), Line, Dtor, 2715 ID, OffloadEntriesInfoManagerTy::OMPTargetRegionEntryDtor); 2716 } 2717 return CGM.getLangOpts().OpenMPIsDevice; 2718 } 2719 2720 Address CGOpenMPRuntime::getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, 2721 QualType VarType, 2722 StringRef Name) { 2723 std::string Suffix = getName({"artificial", ""}); 2724 std::string CacheSuffix = getName({"cache", ""}); 2725 llvm::Type *VarLVType = CGF.ConvertTypeForMem(VarType); 2726 llvm::Value *GAddr = 2727 getOrCreateInternalVariable(VarLVType, Twine(Name).concat(Suffix)); 2728 llvm::Value *Args[] = { 2729 emitUpdateLocation(CGF, SourceLocation()), 2730 getThreadID(CGF, SourceLocation()), 2731 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(GAddr, CGM.VoidPtrTy), 2732 CGF.Builder.CreateIntCast(CGF.getTypeSize(VarType), CGM.SizeTy, 2733 /*IsSigned=*/false), 2734 getOrCreateInternalVariable( 2735 CGM.VoidPtrPtrTy, Twine(Name).concat(Suffix).concat(CacheSuffix))}; 2736 return Address( 2737 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 2738 CGF.EmitRuntimeCall( 2739 createRuntimeFunction(OMPRTL__kmpc_threadprivate_cached), Args), 2740 VarLVType->getPointerTo(/*AddrSpace=*/0)), 2741 CGM.getPointerAlign()); 2742 } 2743 2744 void CGOpenMPRuntime::emitOMPIfClause(CodeGenFunction &CGF, const Expr *Cond, 2745 const RegionCodeGenTy &ThenGen, 2746 const RegionCodeGenTy &ElseGen) { 2747 CodeGenFunction::LexicalScope ConditionScope(CGF, Cond->getSourceRange()); 2748 2749 // If the condition constant folds and can be elided, try to avoid emitting 2750 // the condition and the dead arm of the if/else. 2751 bool CondConstant; 2752 if (CGF.ConstantFoldsToSimpleInteger(Cond, CondConstant)) { 2753 if (CondConstant) 2754 ThenGen(CGF); 2755 else 2756 ElseGen(CGF); 2757 return; 2758 } 2759 2760 // Otherwise, the condition did not fold, or we couldn't elide it. Just 2761 // emit the conditional branch. 2762 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("omp_if.then"); 2763 llvm::BasicBlock *ElseBlock = CGF.createBasicBlock("omp_if.else"); 2764 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("omp_if.end"); 2765 CGF.EmitBranchOnBoolExpr(Cond, ThenBlock, ElseBlock, /*TrueCount=*/0); 2766 2767 // Emit the 'then' code. 2768 CGF.EmitBlock(ThenBlock); 2769 ThenGen(CGF); 2770 CGF.EmitBranch(ContBlock); 2771 // Emit the 'else' code if present. 2772 // There is no need to emit line number for unconditional branch. 2773 (void)ApplyDebugLocation::CreateEmpty(CGF); 2774 CGF.EmitBlock(ElseBlock); 2775 ElseGen(CGF); 2776 // There is no need to emit line number for unconditional branch. 2777 (void)ApplyDebugLocation::CreateEmpty(CGF); 2778 CGF.EmitBranch(ContBlock); 2779 // Emit the continuation block for code after the if. 2780 CGF.EmitBlock(ContBlock, /*IsFinished=*/true); 2781 } 2782 2783 void CGOpenMPRuntime::emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, 2784 llvm::Value *OutlinedFn, 2785 ArrayRef<llvm::Value *> CapturedVars, 2786 const Expr *IfCond) { 2787 if (!CGF.HaveInsertPoint()) 2788 return; 2789 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); 2790 auto &&ThenGen = [OutlinedFn, CapturedVars, RTLoc](CodeGenFunction &CGF, 2791 PrePostActionTy &) { 2792 // Build call __kmpc_fork_call(loc, n, microtask, var1, .., varn); 2793 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 2794 llvm::Value *Args[] = { 2795 RTLoc, 2796 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars 2797 CGF.Builder.CreateBitCast(OutlinedFn, RT.getKmpc_MicroPointerTy())}; 2798 llvm::SmallVector<llvm::Value *, 16> RealArgs; 2799 RealArgs.append(std::begin(Args), std::end(Args)); 2800 RealArgs.append(CapturedVars.begin(), CapturedVars.end()); 2801 2802 llvm::Value *RTLFn = RT.createRuntimeFunction(OMPRTL__kmpc_fork_call); 2803 CGF.EmitRuntimeCall(RTLFn, RealArgs); 2804 }; 2805 auto &&ElseGen = [OutlinedFn, CapturedVars, RTLoc, Loc](CodeGenFunction &CGF, 2806 PrePostActionTy &) { 2807 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 2808 llvm::Value *ThreadID = RT.getThreadID(CGF, Loc); 2809 // Build calls: 2810 // __kmpc_serialized_parallel(&Loc, GTid); 2811 llvm::Value *Args[] = {RTLoc, ThreadID}; 2812 CGF.EmitRuntimeCall( 2813 RT.createRuntimeFunction(OMPRTL__kmpc_serialized_parallel), Args); 2814 2815 // OutlinedFn(>id, &zero, CapturedStruct); 2816 Address ZeroAddr = CGF.CreateDefaultAlignTempAlloca(CGF.Int32Ty, 2817 /*Name*/ ".zero.addr"); 2818 CGF.InitTempAlloca(ZeroAddr, CGF.Builder.getInt32(/*C*/ 0)); 2819 llvm::SmallVector<llvm::Value *, 16> OutlinedFnArgs; 2820 // ThreadId for serialized parallels is 0. 2821 OutlinedFnArgs.push_back(ZeroAddr.getPointer()); 2822 OutlinedFnArgs.push_back(ZeroAddr.getPointer()); 2823 OutlinedFnArgs.append(CapturedVars.begin(), CapturedVars.end()); 2824 RT.emitOutlinedFunctionCall(CGF, Loc, OutlinedFn, OutlinedFnArgs); 2825 2826 // __kmpc_end_serialized_parallel(&Loc, GTid); 2827 llvm::Value *EndArgs[] = {RT.emitUpdateLocation(CGF, Loc), ThreadID}; 2828 CGF.EmitRuntimeCall( 2829 RT.createRuntimeFunction(OMPRTL__kmpc_end_serialized_parallel), 2830 EndArgs); 2831 }; 2832 if (IfCond) { 2833 emitOMPIfClause(CGF, IfCond, ThenGen, ElseGen); 2834 } else { 2835 RegionCodeGenTy ThenRCG(ThenGen); 2836 ThenRCG(CGF); 2837 } 2838 } 2839 2840 // If we're inside an (outlined) parallel region, use the region info's 2841 // thread-ID variable (it is passed in a first argument of the outlined function 2842 // as "kmp_int32 *gtid"). Otherwise, if we're not inside parallel region, but in 2843 // regular serial code region, get thread ID by calling kmp_int32 2844 // kmpc_global_thread_num(ident_t *loc), stash this thread ID in a temporary and 2845 // return the address of that temp. 2846 Address CGOpenMPRuntime::emitThreadIDAddress(CodeGenFunction &CGF, 2847 SourceLocation Loc) { 2848 if (auto *OMPRegionInfo = 2849 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 2850 if (OMPRegionInfo->getThreadIDVariable()) 2851 return OMPRegionInfo->getThreadIDVariableLValue(CGF).getAddress(); 2852 2853 llvm::Value *ThreadID = getThreadID(CGF, Loc); 2854 QualType Int32Ty = 2855 CGF.getContext().getIntTypeForBitwidth(/*DestWidth*/ 32, /*Signed*/ true); 2856 Address ThreadIDTemp = CGF.CreateMemTemp(Int32Ty, /*Name*/ ".threadid_temp."); 2857 CGF.EmitStoreOfScalar(ThreadID, 2858 CGF.MakeAddrLValue(ThreadIDTemp, Int32Ty)); 2859 2860 return ThreadIDTemp; 2861 } 2862 2863 llvm::Constant * 2864 CGOpenMPRuntime::getOrCreateInternalVariable(llvm::Type *Ty, 2865 const llvm::Twine &Name) { 2866 SmallString<256> Buffer; 2867 llvm::raw_svector_ostream Out(Buffer); 2868 Out << Name; 2869 StringRef RuntimeName = Out.str(); 2870 auto &Elem = *InternalVars.try_emplace(RuntimeName, nullptr).first; 2871 if (Elem.second) { 2872 assert(Elem.second->getType()->getPointerElementType() == Ty && 2873 "OMP internal variable has different type than requested"); 2874 return &*Elem.second; 2875 } 2876 2877 return Elem.second = new llvm::GlobalVariable( 2878 CGM.getModule(), Ty, /*IsConstant*/ false, 2879 llvm::GlobalValue::CommonLinkage, llvm::Constant::getNullValue(Ty), 2880 Elem.first()); 2881 } 2882 2883 llvm::Value *CGOpenMPRuntime::getCriticalRegionLock(StringRef CriticalName) { 2884 std::string Prefix = Twine("gomp_critical_user_", CriticalName).str(); 2885 std::string Name = getName({Prefix, "var"}); 2886 return getOrCreateInternalVariable(KmpCriticalNameTy, Name); 2887 } 2888 2889 namespace { 2890 /// Common pre(post)-action for different OpenMP constructs. 2891 class CommonActionTy final : public PrePostActionTy { 2892 llvm::Value *EnterCallee; 2893 ArrayRef<llvm::Value *> EnterArgs; 2894 llvm::Value *ExitCallee; 2895 ArrayRef<llvm::Value *> ExitArgs; 2896 bool Conditional; 2897 llvm::BasicBlock *ContBlock = nullptr; 2898 2899 public: 2900 CommonActionTy(llvm::Value *EnterCallee, ArrayRef<llvm::Value *> EnterArgs, 2901 llvm::Value *ExitCallee, ArrayRef<llvm::Value *> ExitArgs, 2902 bool Conditional = false) 2903 : EnterCallee(EnterCallee), EnterArgs(EnterArgs), ExitCallee(ExitCallee), 2904 ExitArgs(ExitArgs), Conditional(Conditional) {} 2905 void Enter(CodeGenFunction &CGF) override { 2906 llvm::Value *EnterRes = CGF.EmitRuntimeCall(EnterCallee, EnterArgs); 2907 if (Conditional) { 2908 llvm::Value *CallBool = CGF.Builder.CreateIsNotNull(EnterRes); 2909 auto *ThenBlock = CGF.createBasicBlock("omp_if.then"); 2910 ContBlock = CGF.createBasicBlock("omp_if.end"); 2911 // Generate the branch (If-stmt) 2912 CGF.Builder.CreateCondBr(CallBool, ThenBlock, ContBlock); 2913 CGF.EmitBlock(ThenBlock); 2914 } 2915 } 2916 void Done(CodeGenFunction &CGF) { 2917 // Emit the rest of blocks/branches 2918 CGF.EmitBranch(ContBlock); 2919 CGF.EmitBlock(ContBlock, true); 2920 } 2921 void Exit(CodeGenFunction &CGF) override { 2922 CGF.EmitRuntimeCall(ExitCallee, ExitArgs); 2923 } 2924 }; 2925 } // anonymous namespace 2926 2927 void CGOpenMPRuntime::emitCriticalRegion(CodeGenFunction &CGF, 2928 StringRef CriticalName, 2929 const RegionCodeGenTy &CriticalOpGen, 2930 SourceLocation Loc, const Expr *Hint) { 2931 // __kmpc_critical[_with_hint](ident_t *, gtid, Lock[, hint]); 2932 // CriticalOpGen(); 2933 // __kmpc_end_critical(ident_t *, gtid, Lock); 2934 // Prepare arguments and build a call to __kmpc_critical 2935 if (!CGF.HaveInsertPoint()) 2936 return; 2937 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 2938 getCriticalRegionLock(CriticalName)}; 2939 llvm::SmallVector<llvm::Value *, 4> EnterArgs(std::begin(Args), 2940 std::end(Args)); 2941 if (Hint) { 2942 EnterArgs.push_back(CGF.Builder.CreateIntCast( 2943 CGF.EmitScalarExpr(Hint), CGM.IntPtrTy, /*isSigned=*/false)); 2944 } 2945 CommonActionTy Action( 2946 createRuntimeFunction(Hint ? OMPRTL__kmpc_critical_with_hint 2947 : OMPRTL__kmpc_critical), 2948 EnterArgs, createRuntimeFunction(OMPRTL__kmpc_end_critical), Args); 2949 CriticalOpGen.setAction(Action); 2950 emitInlinedDirective(CGF, OMPD_critical, CriticalOpGen); 2951 } 2952 2953 void CGOpenMPRuntime::emitMasterRegion(CodeGenFunction &CGF, 2954 const RegionCodeGenTy &MasterOpGen, 2955 SourceLocation Loc) { 2956 if (!CGF.HaveInsertPoint()) 2957 return; 2958 // if(__kmpc_master(ident_t *, gtid)) { 2959 // MasterOpGen(); 2960 // __kmpc_end_master(ident_t *, gtid); 2961 // } 2962 // Prepare arguments and build a call to __kmpc_master 2963 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 2964 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_master), Args, 2965 createRuntimeFunction(OMPRTL__kmpc_end_master), Args, 2966 /*Conditional=*/true); 2967 MasterOpGen.setAction(Action); 2968 emitInlinedDirective(CGF, OMPD_master, MasterOpGen); 2969 Action.Done(CGF); 2970 } 2971 2972 void CGOpenMPRuntime::emitTaskyieldCall(CodeGenFunction &CGF, 2973 SourceLocation Loc) { 2974 if (!CGF.HaveInsertPoint()) 2975 return; 2976 // Build call __kmpc_omp_taskyield(loc, thread_id, 0); 2977 llvm::Value *Args[] = { 2978 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 2979 llvm::ConstantInt::get(CGM.IntTy, /*V=*/0, /*isSigned=*/true)}; 2980 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskyield), Args); 2981 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 2982 Region->emitUntiedSwitch(CGF); 2983 } 2984 2985 void CGOpenMPRuntime::emitTaskgroupRegion(CodeGenFunction &CGF, 2986 const RegionCodeGenTy &TaskgroupOpGen, 2987 SourceLocation Loc) { 2988 if (!CGF.HaveInsertPoint()) 2989 return; 2990 // __kmpc_taskgroup(ident_t *, gtid); 2991 // TaskgroupOpGen(); 2992 // __kmpc_end_taskgroup(ident_t *, gtid); 2993 // Prepare arguments and build a call to __kmpc_taskgroup 2994 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 2995 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_taskgroup), Args, 2996 createRuntimeFunction(OMPRTL__kmpc_end_taskgroup), 2997 Args); 2998 TaskgroupOpGen.setAction(Action); 2999 emitInlinedDirective(CGF, OMPD_taskgroup, TaskgroupOpGen); 3000 } 3001 3002 /// Given an array of pointers to variables, project the address of a 3003 /// given variable. 3004 static Address emitAddrOfVarFromArray(CodeGenFunction &CGF, Address Array, 3005 unsigned Index, const VarDecl *Var) { 3006 // Pull out the pointer to the variable. 3007 Address PtrAddr = 3008 CGF.Builder.CreateConstArrayGEP(Array, Index, CGF.getPointerSize()); 3009 llvm::Value *Ptr = CGF.Builder.CreateLoad(PtrAddr); 3010 3011 Address Addr = Address(Ptr, CGF.getContext().getDeclAlign(Var)); 3012 Addr = CGF.Builder.CreateElementBitCast( 3013 Addr, CGF.ConvertTypeForMem(Var->getType())); 3014 return Addr; 3015 } 3016 3017 static llvm::Value *emitCopyprivateCopyFunction( 3018 CodeGenModule &CGM, llvm::Type *ArgsType, 3019 ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, 3020 ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps, 3021 SourceLocation Loc) { 3022 ASTContext &C = CGM.getContext(); 3023 // void copy_func(void *LHSArg, void *RHSArg); 3024 FunctionArgList Args; 3025 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 3026 ImplicitParamDecl::Other); 3027 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 3028 ImplicitParamDecl::Other); 3029 Args.push_back(&LHSArg); 3030 Args.push_back(&RHSArg); 3031 const auto &CGFI = 3032 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 3033 std::string Name = 3034 CGM.getOpenMPRuntime().getName({"omp", "copyprivate", "copy_func"}); 3035 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), 3036 llvm::GlobalValue::InternalLinkage, Name, 3037 &CGM.getModule()); 3038 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); 3039 Fn->setDoesNotRecurse(); 3040 CodeGenFunction CGF(CGM); 3041 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); 3042 // Dest = (void*[n])(LHSArg); 3043 // Src = (void*[n])(RHSArg); 3044 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 3045 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), 3046 ArgsType), CGF.getPointerAlign()); 3047 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 3048 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), 3049 ArgsType), CGF.getPointerAlign()); 3050 // *(Type0*)Dst[0] = *(Type0*)Src[0]; 3051 // *(Type1*)Dst[1] = *(Type1*)Src[1]; 3052 // ... 3053 // *(Typen*)Dst[n] = *(Typen*)Src[n]; 3054 for (unsigned I = 0, E = AssignmentOps.size(); I < E; ++I) { 3055 const auto *DestVar = 3056 cast<VarDecl>(cast<DeclRefExpr>(DestExprs[I])->getDecl()); 3057 Address DestAddr = emitAddrOfVarFromArray(CGF, LHS, I, DestVar); 3058 3059 const auto *SrcVar = 3060 cast<VarDecl>(cast<DeclRefExpr>(SrcExprs[I])->getDecl()); 3061 Address SrcAddr = emitAddrOfVarFromArray(CGF, RHS, I, SrcVar); 3062 3063 const auto *VD = cast<DeclRefExpr>(CopyprivateVars[I])->getDecl(); 3064 QualType Type = VD->getType(); 3065 CGF.EmitOMPCopy(Type, DestAddr, SrcAddr, DestVar, SrcVar, AssignmentOps[I]); 3066 } 3067 CGF.FinishFunction(); 3068 return Fn; 3069 } 3070 3071 void CGOpenMPRuntime::emitSingleRegion(CodeGenFunction &CGF, 3072 const RegionCodeGenTy &SingleOpGen, 3073 SourceLocation Loc, 3074 ArrayRef<const Expr *> CopyprivateVars, 3075 ArrayRef<const Expr *> SrcExprs, 3076 ArrayRef<const Expr *> DstExprs, 3077 ArrayRef<const Expr *> AssignmentOps) { 3078 if (!CGF.HaveInsertPoint()) 3079 return; 3080 assert(CopyprivateVars.size() == SrcExprs.size() && 3081 CopyprivateVars.size() == DstExprs.size() && 3082 CopyprivateVars.size() == AssignmentOps.size()); 3083 ASTContext &C = CGM.getContext(); 3084 // int32 did_it = 0; 3085 // if(__kmpc_single(ident_t *, gtid)) { 3086 // SingleOpGen(); 3087 // __kmpc_end_single(ident_t *, gtid); 3088 // did_it = 1; 3089 // } 3090 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, 3091 // <copy_func>, did_it); 3092 3093 Address DidIt = Address::invalid(); 3094 if (!CopyprivateVars.empty()) { 3095 // int32 did_it = 0; 3096 QualType KmpInt32Ty = 3097 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 3098 DidIt = CGF.CreateMemTemp(KmpInt32Ty, ".omp.copyprivate.did_it"); 3099 CGF.Builder.CreateStore(CGF.Builder.getInt32(0), DidIt); 3100 } 3101 // Prepare arguments and build a call to __kmpc_single 3102 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3103 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_single), Args, 3104 createRuntimeFunction(OMPRTL__kmpc_end_single), Args, 3105 /*Conditional=*/true); 3106 SingleOpGen.setAction(Action); 3107 emitInlinedDirective(CGF, OMPD_single, SingleOpGen); 3108 if (DidIt.isValid()) { 3109 // did_it = 1; 3110 CGF.Builder.CreateStore(CGF.Builder.getInt32(1), DidIt); 3111 } 3112 Action.Done(CGF); 3113 // call __kmpc_copyprivate(ident_t *, gtid, <buf_size>, <copyprivate list>, 3114 // <copy_func>, did_it); 3115 if (DidIt.isValid()) { 3116 llvm::APInt ArraySize(/*unsigned int numBits=*/32, CopyprivateVars.size()); 3117 QualType CopyprivateArrayTy = 3118 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal, 3119 /*IndexTypeQuals=*/0); 3120 // Create a list of all private variables for copyprivate. 3121 Address CopyprivateList = 3122 CGF.CreateMemTemp(CopyprivateArrayTy, ".omp.copyprivate.cpr_list"); 3123 for (unsigned I = 0, E = CopyprivateVars.size(); I < E; ++I) { 3124 Address Elem = CGF.Builder.CreateConstArrayGEP( 3125 CopyprivateList, I, CGF.getPointerSize()); 3126 CGF.Builder.CreateStore( 3127 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 3128 CGF.EmitLValue(CopyprivateVars[I]).getPointer(), CGF.VoidPtrTy), 3129 Elem); 3130 } 3131 // Build function that copies private values from single region to all other 3132 // threads in the corresponding parallel region. 3133 llvm::Value *CpyFn = emitCopyprivateCopyFunction( 3134 CGM, CGF.ConvertTypeForMem(CopyprivateArrayTy)->getPointerTo(), 3135 CopyprivateVars, SrcExprs, DstExprs, AssignmentOps, Loc); 3136 llvm::Value *BufSize = CGF.getTypeSize(CopyprivateArrayTy); 3137 Address CL = 3138 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(CopyprivateList, 3139 CGF.VoidPtrTy); 3140 llvm::Value *DidItVal = CGF.Builder.CreateLoad(DidIt); 3141 llvm::Value *Args[] = { 3142 emitUpdateLocation(CGF, Loc), // ident_t *<loc> 3143 getThreadID(CGF, Loc), // i32 <gtid> 3144 BufSize, // size_t <buf_size> 3145 CL.getPointer(), // void *<copyprivate list> 3146 CpyFn, // void (*) (void *, void *) <copy_func> 3147 DidItVal // i32 did_it 3148 }; 3149 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_copyprivate), Args); 3150 } 3151 } 3152 3153 void CGOpenMPRuntime::emitOrderedRegion(CodeGenFunction &CGF, 3154 const RegionCodeGenTy &OrderedOpGen, 3155 SourceLocation Loc, bool IsThreads) { 3156 if (!CGF.HaveInsertPoint()) 3157 return; 3158 // __kmpc_ordered(ident_t *, gtid); 3159 // OrderedOpGen(); 3160 // __kmpc_end_ordered(ident_t *, gtid); 3161 // Prepare arguments and build a call to __kmpc_ordered 3162 if (IsThreads) { 3163 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3164 CommonActionTy Action(createRuntimeFunction(OMPRTL__kmpc_ordered), Args, 3165 createRuntimeFunction(OMPRTL__kmpc_end_ordered), 3166 Args); 3167 OrderedOpGen.setAction(Action); 3168 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); 3169 return; 3170 } 3171 emitInlinedDirective(CGF, OMPD_ordered, OrderedOpGen); 3172 } 3173 3174 void CGOpenMPRuntime::emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, 3175 OpenMPDirectiveKind Kind, bool EmitChecks, 3176 bool ForceSimpleCall) { 3177 if (!CGF.HaveInsertPoint()) 3178 return; 3179 // Build call __kmpc_cancel_barrier(loc, thread_id); 3180 // Build call __kmpc_barrier(loc, thread_id); 3181 unsigned Flags; 3182 if (Kind == OMPD_for) 3183 Flags = OMP_IDENT_BARRIER_IMPL_FOR; 3184 else if (Kind == OMPD_sections) 3185 Flags = OMP_IDENT_BARRIER_IMPL_SECTIONS; 3186 else if (Kind == OMPD_single) 3187 Flags = OMP_IDENT_BARRIER_IMPL_SINGLE; 3188 else if (Kind == OMPD_barrier) 3189 Flags = OMP_IDENT_BARRIER_EXPL; 3190 else 3191 Flags = OMP_IDENT_BARRIER_IMPL; 3192 // Build call __kmpc_cancel_barrier(loc, thread_id) or __kmpc_barrier(loc, 3193 // thread_id); 3194 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc, Flags), 3195 getThreadID(CGF, Loc)}; 3196 if (auto *OMPRegionInfo = 3197 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 3198 if (!ForceSimpleCall && OMPRegionInfo->hasCancel()) { 3199 llvm::Value *Result = CGF.EmitRuntimeCall( 3200 createRuntimeFunction(OMPRTL__kmpc_cancel_barrier), Args); 3201 if (EmitChecks) { 3202 // if (__kmpc_cancel_barrier()) { 3203 // exit from construct; 3204 // } 3205 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); 3206 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); 3207 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); 3208 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); 3209 CGF.EmitBlock(ExitBB); 3210 // exit from construct; 3211 CodeGenFunction::JumpDest CancelDestination = 3212 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); 3213 CGF.EmitBranchThroughCleanup(CancelDestination); 3214 CGF.EmitBlock(ContBB, /*IsFinished=*/true); 3215 } 3216 return; 3217 } 3218 } 3219 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_barrier), Args); 3220 } 3221 3222 /// Map the OpenMP loop schedule to the runtime enumeration. 3223 static OpenMPSchedType getRuntimeSchedule(OpenMPScheduleClauseKind ScheduleKind, 3224 bool Chunked, bool Ordered) { 3225 switch (ScheduleKind) { 3226 case OMPC_SCHEDULE_static: 3227 return Chunked ? (Ordered ? OMP_ord_static_chunked : OMP_sch_static_chunked) 3228 : (Ordered ? OMP_ord_static : OMP_sch_static); 3229 case OMPC_SCHEDULE_dynamic: 3230 return Ordered ? OMP_ord_dynamic_chunked : OMP_sch_dynamic_chunked; 3231 case OMPC_SCHEDULE_guided: 3232 return Ordered ? OMP_ord_guided_chunked : OMP_sch_guided_chunked; 3233 case OMPC_SCHEDULE_runtime: 3234 return Ordered ? OMP_ord_runtime : OMP_sch_runtime; 3235 case OMPC_SCHEDULE_auto: 3236 return Ordered ? OMP_ord_auto : OMP_sch_auto; 3237 case OMPC_SCHEDULE_unknown: 3238 assert(!Chunked && "chunk was specified but schedule kind not known"); 3239 return Ordered ? OMP_ord_static : OMP_sch_static; 3240 } 3241 llvm_unreachable("Unexpected runtime schedule"); 3242 } 3243 3244 /// Map the OpenMP distribute schedule to the runtime enumeration. 3245 static OpenMPSchedType 3246 getRuntimeSchedule(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) { 3247 // only static is allowed for dist_schedule 3248 return Chunked ? OMP_dist_sch_static_chunked : OMP_dist_sch_static; 3249 } 3250 3251 bool CGOpenMPRuntime::isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, 3252 bool Chunked) const { 3253 OpenMPSchedType Schedule = 3254 getRuntimeSchedule(ScheduleKind, Chunked, /*Ordered=*/false); 3255 return Schedule == OMP_sch_static; 3256 } 3257 3258 bool CGOpenMPRuntime::isStaticNonchunked( 3259 OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const { 3260 OpenMPSchedType Schedule = getRuntimeSchedule(ScheduleKind, Chunked); 3261 return Schedule == OMP_dist_sch_static; 3262 } 3263 3264 3265 bool CGOpenMPRuntime::isDynamic(OpenMPScheduleClauseKind ScheduleKind) const { 3266 OpenMPSchedType Schedule = 3267 getRuntimeSchedule(ScheduleKind, /*Chunked=*/false, /*Ordered=*/false); 3268 assert(Schedule != OMP_sch_static_chunked && "cannot be chunked here"); 3269 return Schedule != OMP_sch_static; 3270 } 3271 3272 static int addMonoNonMonoModifier(OpenMPSchedType Schedule, 3273 OpenMPScheduleClauseModifier M1, 3274 OpenMPScheduleClauseModifier M2) { 3275 int Modifier = 0; 3276 switch (M1) { 3277 case OMPC_SCHEDULE_MODIFIER_monotonic: 3278 Modifier = OMP_sch_modifier_monotonic; 3279 break; 3280 case OMPC_SCHEDULE_MODIFIER_nonmonotonic: 3281 Modifier = OMP_sch_modifier_nonmonotonic; 3282 break; 3283 case OMPC_SCHEDULE_MODIFIER_simd: 3284 if (Schedule == OMP_sch_static_chunked) 3285 Schedule = OMP_sch_static_balanced_chunked; 3286 break; 3287 case OMPC_SCHEDULE_MODIFIER_last: 3288 case OMPC_SCHEDULE_MODIFIER_unknown: 3289 break; 3290 } 3291 switch (M2) { 3292 case OMPC_SCHEDULE_MODIFIER_monotonic: 3293 Modifier = OMP_sch_modifier_monotonic; 3294 break; 3295 case OMPC_SCHEDULE_MODIFIER_nonmonotonic: 3296 Modifier = OMP_sch_modifier_nonmonotonic; 3297 break; 3298 case OMPC_SCHEDULE_MODIFIER_simd: 3299 if (Schedule == OMP_sch_static_chunked) 3300 Schedule = OMP_sch_static_balanced_chunked; 3301 break; 3302 case OMPC_SCHEDULE_MODIFIER_last: 3303 case OMPC_SCHEDULE_MODIFIER_unknown: 3304 break; 3305 } 3306 return Schedule | Modifier; 3307 } 3308 3309 void CGOpenMPRuntime::emitForDispatchInit( 3310 CodeGenFunction &CGF, SourceLocation Loc, 3311 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, 3312 bool Ordered, const DispatchRTInput &DispatchValues) { 3313 if (!CGF.HaveInsertPoint()) 3314 return; 3315 OpenMPSchedType Schedule = getRuntimeSchedule( 3316 ScheduleKind.Schedule, DispatchValues.Chunk != nullptr, Ordered); 3317 assert(Ordered || 3318 (Schedule != OMP_sch_static && Schedule != OMP_sch_static_chunked && 3319 Schedule != OMP_ord_static && Schedule != OMP_ord_static_chunked && 3320 Schedule != OMP_sch_static_balanced_chunked)); 3321 // Call __kmpc_dispatch_init( 3322 // ident_t *loc, kmp_int32 tid, kmp_int32 schedule, 3323 // kmp_int[32|64] lower, kmp_int[32|64] upper, 3324 // kmp_int[32|64] stride, kmp_int[32|64] chunk); 3325 3326 // If the Chunk was not specified in the clause - use default value 1. 3327 llvm::Value *Chunk = DispatchValues.Chunk ? DispatchValues.Chunk 3328 : CGF.Builder.getIntN(IVSize, 1); 3329 llvm::Value *Args[] = { 3330 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3331 CGF.Builder.getInt32(addMonoNonMonoModifier( 3332 Schedule, ScheduleKind.M1, ScheduleKind.M2)), // Schedule type 3333 DispatchValues.LB, // Lower 3334 DispatchValues.UB, // Upper 3335 CGF.Builder.getIntN(IVSize, 1), // Stride 3336 Chunk // Chunk 3337 }; 3338 CGF.EmitRuntimeCall(createDispatchInitFunction(IVSize, IVSigned), Args); 3339 } 3340 3341 static void emitForStaticInitCall( 3342 CodeGenFunction &CGF, llvm::Value *UpdateLocation, llvm::Value *ThreadId, 3343 llvm::Constant *ForStaticInitFunction, OpenMPSchedType Schedule, 3344 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 3345 const CGOpenMPRuntime::StaticRTInput &Values) { 3346 if (!CGF.HaveInsertPoint()) 3347 return; 3348 3349 assert(!Values.Ordered); 3350 assert(Schedule == OMP_sch_static || Schedule == OMP_sch_static_chunked || 3351 Schedule == OMP_sch_static_balanced_chunked || 3352 Schedule == OMP_ord_static || Schedule == OMP_ord_static_chunked || 3353 Schedule == OMP_dist_sch_static || 3354 Schedule == OMP_dist_sch_static_chunked); 3355 3356 // Call __kmpc_for_static_init( 3357 // ident_t *loc, kmp_int32 tid, kmp_int32 schedtype, 3358 // kmp_int32 *p_lastiter, kmp_int[32|64] *p_lower, 3359 // kmp_int[32|64] *p_upper, kmp_int[32|64] *p_stride, 3360 // kmp_int[32|64] incr, kmp_int[32|64] chunk); 3361 llvm::Value *Chunk = Values.Chunk; 3362 if (Chunk == nullptr) { 3363 assert((Schedule == OMP_sch_static || Schedule == OMP_ord_static || 3364 Schedule == OMP_dist_sch_static) && 3365 "expected static non-chunked schedule"); 3366 // If the Chunk was not specified in the clause - use default value 1. 3367 Chunk = CGF.Builder.getIntN(Values.IVSize, 1); 3368 } else { 3369 assert((Schedule == OMP_sch_static_chunked || 3370 Schedule == OMP_sch_static_balanced_chunked || 3371 Schedule == OMP_ord_static_chunked || 3372 Schedule == OMP_dist_sch_static_chunked) && 3373 "expected static chunked schedule"); 3374 } 3375 llvm::Value *Args[] = { 3376 UpdateLocation, 3377 ThreadId, 3378 CGF.Builder.getInt32(addMonoNonMonoModifier(Schedule, M1, 3379 M2)), // Schedule type 3380 Values.IL.getPointer(), // &isLastIter 3381 Values.LB.getPointer(), // &LB 3382 Values.UB.getPointer(), // &UB 3383 Values.ST.getPointer(), // &Stride 3384 CGF.Builder.getIntN(Values.IVSize, 1), // Incr 3385 Chunk // Chunk 3386 }; 3387 CGF.EmitRuntimeCall(ForStaticInitFunction, Args); 3388 } 3389 3390 void CGOpenMPRuntime::emitForStaticInit(CodeGenFunction &CGF, 3391 SourceLocation Loc, 3392 OpenMPDirectiveKind DKind, 3393 const OpenMPScheduleTy &ScheduleKind, 3394 const StaticRTInput &Values) { 3395 OpenMPSchedType ScheduleNum = getRuntimeSchedule( 3396 ScheduleKind.Schedule, Values.Chunk != nullptr, Values.Ordered); 3397 assert(isOpenMPWorksharingDirective(DKind) && 3398 "Expected loop-based or sections-based directive."); 3399 llvm::Value *UpdatedLocation = emitUpdateLocation(CGF, Loc, 3400 isOpenMPLoopDirective(DKind) 3401 ? OMP_IDENT_WORK_LOOP 3402 : OMP_IDENT_WORK_SECTIONS); 3403 llvm::Value *ThreadId = getThreadID(CGF, Loc); 3404 llvm::Constant *StaticInitFunction = 3405 createForStaticInitFunction(Values.IVSize, Values.IVSigned); 3406 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, 3407 ScheduleNum, ScheduleKind.M1, ScheduleKind.M2, Values); 3408 } 3409 3410 void CGOpenMPRuntime::emitDistributeStaticInit( 3411 CodeGenFunction &CGF, SourceLocation Loc, 3412 OpenMPDistScheduleClauseKind SchedKind, 3413 const CGOpenMPRuntime::StaticRTInput &Values) { 3414 OpenMPSchedType ScheduleNum = 3415 getRuntimeSchedule(SchedKind, Values.Chunk != nullptr); 3416 llvm::Value *UpdatedLocation = 3417 emitUpdateLocation(CGF, Loc, OMP_IDENT_WORK_DISTRIBUTE); 3418 llvm::Value *ThreadId = getThreadID(CGF, Loc); 3419 llvm::Constant *StaticInitFunction = 3420 createForStaticInitFunction(Values.IVSize, Values.IVSigned); 3421 emitForStaticInitCall(CGF, UpdatedLocation, ThreadId, StaticInitFunction, 3422 ScheduleNum, OMPC_SCHEDULE_MODIFIER_unknown, 3423 OMPC_SCHEDULE_MODIFIER_unknown, Values); 3424 } 3425 3426 void CGOpenMPRuntime::emitForStaticFinish(CodeGenFunction &CGF, 3427 SourceLocation Loc, 3428 OpenMPDirectiveKind DKind) { 3429 if (!CGF.HaveInsertPoint()) 3430 return; 3431 // Call __kmpc_for_static_fini(ident_t *loc, kmp_int32 tid); 3432 llvm::Value *Args[] = { 3433 emitUpdateLocation(CGF, Loc, 3434 isOpenMPDistributeDirective(DKind) 3435 ? OMP_IDENT_WORK_DISTRIBUTE 3436 : isOpenMPLoopDirective(DKind) 3437 ? OMP_IDENT_WORK_LOOP 3438 : OMP_IDENT_WORK_SECTIONS), 3439 getThreadID(CGF, Loc)}; 3440 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_for_static_fini), 3441 Args); 3442 } 3443 3444 void CGOpenMPRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF, 3445 SourceLocation Loc, 3446 unsigned IVSize, 3447 bool IVSigned) { 3448 if (!CGF.HaveInsertPoint()) 3449 return; 3450 // Call __kmpc_for_dynamic_fini_(4|8)[u](ident_t *loc, kmp_int32 tid); 3451 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 3452 CGF.EmitRuntimeCall(createDispatchFiniFunction(IVSize, IVSigned), Args); 3453 } 3454 3455 llvm::Value *CGOpenMPRuntime::emitForNext(CodeGenFunction &CGF, 3456 SourceLocation Loc, unsigned IVSize, 3457 bool IVSigned, Address IL, 3458 Address LB, Address UB, 3459 Address ST) { 3460 // Call __kmpc_dispatch_next( 3461 // ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, 3462 // kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, 3463 // kmp_int[32|64] *p_stride); 3464 llvm::Value *Args[] = { 3465 emitUpdateLocation(CGF, Loc), 3466 getThreadID(CGF, Loc), 3467 IL.getPointer(), // &isLastIter 3468 LB.getPointer(), // &Lower 3469 UB.getPointer(), // &Upper 3470 ST.getPointer() // &Stride 3471 }; 3472 llvm::Value *Call = 3473 CGF.EmitRuntimeCall(createDispatchNextFunction(IVSize, IVSigned), Args); 3474 return CGF.EmitScalarConversion( 3475 Call, CGF.getContext().getIntTypeForBitwidth(32, /*Signed=*/1), 3476 CGF.getContext().BoolTy, Loc); 3477 } 3478 3479 void CGOpenMPRuntime::emitNumThreadsClause(CodeGenFunction &CGF, 3480 llvm::Value *NumThreads, 3481 SourceLocation Loc) { 3482 if (!CGF.HaveInsertPoint()) 3483 return; 3484 // Build call __kmpc_push_num_threads(&loc, global_tid, num_threads) 3485 llvm::Value *Args[] = { 3486 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3487 CGF.Builder.CreateIntCast(NumThreads, CGF.Int32Ty, /*isSigned*/ true)}; 3488 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_threads), 3489 Args); 3490 } 3491 3492 void CGOpenMPRuntime::emitProcBindClause(CodeGenFunction &CGF, 3493 OpenMPProcBindClauseKind ProcBind, 3494 SourceLocation Loc) { 3495 if (!CGF.HaveInsertPoint()) 3496 return; 3497 // Constants for proc bind value accepted by the runtime. 3498 enum ProcBindTy { 3499 ProcBindFalse = 0, 3500 ProcBindTrue, 3501 ProcBindMaster, 3502 ProcBindClose, 3503 ProcBindSpread, 3504 ProcBindIntel, 3505 ProcBindDefault 3506 } RuntimeProcBind; 3507 switch (ProcBind) { 3508 case OMPC_PROC_BIND_master: 3509 RuntimeProcBind = ProcBindMaster; 3510 break; 3511 case OMPC_PROC_BIND_close: 3512 RuntimeProcBind = ProcBindClose; 3513 break; 3514 case OMPC_PROC_BIND_spread: 3515 RuntimeProcBind = ProcBindSpread; 3516 break; 3517 case OMPC_PROC_BIND_unknown: 3518 llvm_unreachable("Unsupported proc_bind value."); 3519 } 3520 // Build call __kmpc_push_proc_bind(&loc, global_tid, proc_bind) 3521 llvm::Value *Args[] = { 3522 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 3523 llvm::ConstantInt::get(CGM.IntTy, RuntimeProcBind, /*isSigned=*/true)}; 3524 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_proc_bind), Args); 3525 } 3526 3527 void CGOpenMPRuntime::emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *>, 3528 SourceLocation Loc) { 3529 if (!CGF.HaveInsertPoint()) 3530 return; 3531 // Build call void __kmpc_flush(ident_t *loc) 3532 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_flush), 3533 emitUpdateLocation(CGF, Loc)); 3534 } 3535 3536 namespace { 3537 /// Indexes of fields for type kmp_task_t. 3538 enum KmpTaskTFields { 3539 /// List of shared variables. 3540 KmpTaskTShareds, 3541 /// Task routine. 3542 KmpTaskTRoutine, 3543 /// Partition id for the untied tasks. 3544 KmpTaskTPartId, 3545 /// Function with call of destructors for private variables. 3546 Data1, 3547 /// Task priority. 3548 Data2, 3549 /// (Taskloops only) Lower bound. 3550 KmpTaskTLowerBound, 3551 /// (Taskloops only) Upper bound. 3552 KmpTaskTUpperBound, 3553 /// (Taskloops only) Stride. 3554 KmpTaskTStride, 3555 /// (Taskloops only) Is last iteration flag. 3556 KmpTaskTLastIter, 3557 /// (Taskloops only) Reduction data. 3558 KmpTaskTReductions, 3559 }; 3560 } // anonymous namespace 3561 3562 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::empty() const { 3563 return OffloadEntriesTargetRegion.empty() && 3564 OffloadEntriesDeviceGlobalVar.empty(); 3565 } 3566 3567 /// Initialize target region entry. 3568 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3569 initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 3570 StringRef ParentName, unsigned LineNum, 3571 unsigned Order) { 3572 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is " 3573 "only required for the device " 3574 "code generation."); 3575 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = 3576 OffloadEntryInfoTargetRegion(Order, /*Addr=*/nullptr, /*ID=*/nullptr, 3577 OMPTargetRegionEntryTargetRegion); 3578 ++OffloadingEntriesNum; 3579 } 3580 3581 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3582 registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, 3583 StringRef ParentName, unsigned LineNum, 3584 llvm::Constant *Addr, llvm::Constant *ID, 3585 OMPTargetRegionEntryKind Flags) { 3586 // If we are emitting code for a target, the entry is already initialized, 3587 // only has to be registered. 3588 if (CGM.getLangOpts().OpenMPIsDevice) { 3589 if (!hasTargetRegionEntryInfo(DeviceID, FileID, ParentName, LineNum)) { 3590 unsigned DiagID = CGM.getDiags().getCustomDiagID( 3591 DiagnosticsEngine::Error, 3592 "Unable to find target region on line '%0' in the device code."); 3593 CGM.getDiags().Report(DiagID) << LineNum; 3594 return; 3595 } 3596 auto &Entry = 3597 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum]; 3598 assert(Entry.isValid() && "Entry not initialized!"); 3599 Entry.setAddress(Addr); 3600 Entry.setID(ID); 3601 Entry.setFlags(Flags); 3602 } else { 3603 OffloadEntryInfoTargetRegion Entry(OffloadingEntriesNum, Addr, ID, Flags); 3604 OffloadEntriesTargetRegion[DeviceID][FileID][ParentName][LineNum] = Entry; 3605 ++OffloadingEntriesNum; 3606 } 3607 } 3608 3609 bool CGOpenMPRuntime::OffloadEntriesInfoManagerTy::hasTargetRegionEntryInfo( 3610 unsigned DeviceID, unsigned FileID, StringRef ParentName, 3611 unsigned LineNum) const { 3612 auto PerDevice = OffloadEntriesTargetRegion.find(DeviceID); 3613 if (PerDevice == OffloadEntriesTargetRegion.end()) 3614 return false; 3615 auto PerFile = PerDevice->second.find(FileID); 3616 if (PerFile == PerDevice->second.end()) 3617 return false; 3618 auto PerParentName = PerFile->second.find(ParentName); 3619 if (PerParentName == PerFile->second.end()) 3620 return false; 3621 auto PerLine = PerParentName->second.find(LineNum); 3622 if (PerLine == PerParentName->second.end()) 3623 return false; 3624 // Fail if this entry is already registered. 3625 if (PerLine->second.getAddress() || PerLine->second.getID()) 3626 return false; 3627 return true; 3628 } 3629 3630 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy::actOnTargetRegionEntriesInfo( 3631 const OffloadTargetRegionEntryInfoActTy &Action) { 3632 // Scan all target region entries and perform the provided action. 3633 for (const auto &D : OffloadEntriesTargetRegion) 3634 for (const auto &F : D.second) 3635 for (const auto &P : F.second) 3636 for (const auto &L : P.second) 3637 Action(D.first, F.first, P.first(), L.first, L.second); 3638 } 3639 3640 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3641 initializeDeviceGlobalVarEntryInfo(StringRef Name, 3642 OMPTargetGlobalVarEntryKind Flags, 3643 unsigned Order) { 3644 assert(CGM.getLangOpts().OpenMPIsDevice && "Initialization of entries is " 3645 "only required for the device " 3646 "code generation."); 3647 OffloadEntriesDeviceGlobalVar.try_emplace(Name, Order, Flags); 3648 ++OffloadingEntriesNum; 3649 } 3650 3651 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3652 registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr, 3653 CharUnits VarSize, 3654 OMPTargetGlobalVarEntryKind Flags, 3655 llvm::GlobalValue::LinkageTypes Linkage) { 3656 if (CGM.getLangOpts().OpenMPIsDevice) { 3657 auto &Entry = OffloadEntriesDeviceGlobalVar[VarName]; 3658 assert(Entry.isValid() && Entry.getFlags() == Flags && 3659 "Entry not initialized!"); 3660 assert((!Entry.getAddress() || Entry.getAddress() == Addr) && 3661 "Resetting with the new address."); 3662 if (Entry.getAddress() && hasDeviceGlobalVarEntryInfo(VarName)) 3663 return; 3664 Entry.setAddress(Addr); 3665 Entry.setVarSize(VarSize); 3666 Entry.setLinkage(Linkage); 3667 } else { 3668 if (hasDeviceGlobalVarEntryInfo(VarName)) 3669 return; 3670 OffloadEntriesDeviceGlobalVar.try_emplace( 3671 VarName, OffloadingEntriesNum, Addr, VarSize, Flags, Linkage); 3672 ++OffloadingEntriesNum; 3673 } 3674 } 3675 3676 void CGOpenMPRuntime::OffloadEntriesInfoManagerTy:: 3677 actOnDeviceGlobalVarEntriesInfo( 3678 const OffloadDeviceGlobalVarEntryInfoActTy &Action) { 3679 // Scan all target region entries and perform the provided action. 3680 for (const auto &E : OffloadEntriesDeviceGlobalVar) 3681 Action(E.getKey(), E.getValue()); 3682 } 3683 3684 llvm::Function * 3685 CGOpenMPRuntime::createOffloadingBinaryDescriptorRegistration() { 3686 // If we don't have entries or if we are emitting code for the device, we 3687 // don't need to do anything. 3688 if (CGM.getLangOpts().OpenMPIsDevice || OffloadEntriesInfoManager.empty()) 3689 return nullptr; 3690 3691 llvm::Module &M = CGM.getModule(); 3692 ASTContext &C = CGM.getContext(); 3693 3694 // Get list of devices we care about 3695 const std::vector<llvm::Triple> &Devices = CGM.getLangOpts().OMPTargetTriples; 3696 3697 // We should be creating an offloading descriptor only if there are devices 3698 // specified. 3699 assert(!Devices.empty() && "No OpenMP offloading devices??"); 3700 3701 // Create the external variables that will point to the begin and end of the 3702 // host entries section. These will be defined by the linker. 3703 llvm::Type *OffloadEntryTy = 3704 CGM.getTypes().ConvertTypeForMem(getTgtOffloadEntryQTy()); 3705 std::string EntriesBeginName = getName({"omp_offloading", "entries_begin"}); 3706 auto *HostEntriesBegin = new llvm::GlobalVariable( 3707 M, OffloadEntryTy, /*isConstant=*/true, 3708 llvm::GlobalValue::ExternalLinkage, /*Initializer=*/nullptr, 3709 EntriesBeginName); 3710 std::string EntriesEndName = getName({"omp_offloading", "entries_end"}); 3711 auto *HostEntriesEnd = 3712 new llvm::GlobalVariable(M, OffloadEntryTy, /*isConstant=*/true, 3713 llvm::GlobalValue::ExternalLinkage, 3714 /*Initializer=*/nullptr, EntriesEndName); 3715 3716 // Create all device images 3717 auto *DeviceImageTy = cast<llvm::StructType>( 3718 CGM.getTypes().ConvertTypeForMem(getTgtDeviceImageQTy())); 3719 ConstantInitBuilder DeviceImagesBuilder(CGM); 3720 ConstantArrayBuilder DeviceImagesEntries = 3721 DeviceImagesBuilder.beginArray(DeviceImageTy); 3722 3723 for (const llvm::Triple &Device : Devices) { 3724 StringRef T = Device.getTriple(); 3725 std::string BeginName = getName({"omp_offloading", "img_start", ""}); 3726 auto *ImgBegin = new llvm::GlobalVariable( 3727 M, CGM.Int8Ty, /*isConstant=*/true, 3728 llvm::GlobalValue::ExternalWeakLinkage, 3729 /*Initializer=*/nullptr, Twine(BeginName).concat(T)); 3730 std::string EndName = getName({"omp_offloading", "img_end", ""}); 3731 auto *ImgEnd = new llvm::GlobalVariable( 3732 M, CGM.Int8Ty, /*isConstant=*/true, 3733 llvm::GlobalValue::ExternalWeakLinkage, 3734 /*Initializer=*/nullptr, Twine(EndName).concat(T)); 3735 3736 llvm::Constant *Data[] = {ImgBegin, ImgEnd, HostEntriesBegin, 3737 HostEntriesEnd}; 3738 createConstantGlobalStructAndAddToParent(CGM, getTgtDeviceImageQTy(), Data, 3739 DeviceImagesEntries); 3740 } 3741 3742 // Create device images global array. 3743 std::string ImagesName = getName({"omp_offloading", "device_images"}); 3744 llvm::GlobalVariable *DeviceImages = 3745 DeviceImagesEntries.finishAndCreateGlobal(ImagesName, 3746 CGM.getPointerAlign(), 3747 /*isConstant=*/true); 3748 DeviceImages->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3749 3750 // This is a Zero array to be used in the creation of the constant expressions 3751 llvm::Constant *Index[] = {llvm::Constant::getNullValue(CGM.Int32Ty), 3752 llvm::Constant::getNullValue(CGM.Int32Ty)}; 3753 3754 // Create the target region descriptor. 3755 llvm::Constant *Data[] = { 3756 llvm::ConstantInt::get(CGM.Int32Ty, Devices.size()), 3757 llvm::ConstantExpr::getGetElementPtr(DeviceImages->getValueType(), 3758 DeviceImages, Index), 3759 HostEntriesBegin, HostEntriesEnd}; 3760 std::string Descriptor = getName({"omp_offloading", "descriptor"}); 3761 llvm::GlobalVariable *Desc = createGlobalStruct( 3762 CGM, getTgtBinaryDescriptorQTy(), /*IsConstant=*/true, Data, Descriptor); 3763 3764 // Emit code to register or unregister the descriptor at execution 3765 // startup or closing, respectively. 3766 3767 llvm::Function *UnRegFn; 3768 { 3769 FunctionArgList Args; 3770 ImplicitParamDecl DummyPtr(C, C.VoidPtrTy, ImplicitParamDecl::Other); 3771 Args.push_back(&DummyPtr); 3772 3773 CodeGenFunction CGF(CGM); 3774 // Disable debug info for global (de-)initializer because they are not part 3775 // of some particular construct. 3776 CGF.disableDebugInfo(); 3777 const auto &FI = 3778 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 3779 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 3780 std::string UnregName = getName({"omp_offloading", "descriptor_unreg"}); 3781 UnRegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, UnregName, FI); 3782 CGF.StartFunction(GlobalDecl(), C.VoidTy, UnRegFn, FI, Args); 3783 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_unregister_lib), 3784 Desc); 3785 CGF.FinishFunction(); 3786 } 3787 llvm::Function *RegFn; 3788 { 3789 CodeGenFunction CGF(CGM); 3790 // Disable debug info for global (de-)initializer because they are not part 3791 // of some particular construct. 3792 CGF.disableDebugInfo(); 3793 const auto &FI = CGM.getTypes().arrangeNullaryFunction(); 3794 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI); 3795 3796 // Encode offload target triples into the registration function name. It 3797 // will serve as a comdat key for the registration/unregistration code for 3798 // this particular combination of offloading targets. 3799 SmallVector<StringRef, 4U> RegFnNameParts(Devices.size() + 2U); 3800 RegFnNameParts[0] = "omp_offloading"; 3801 RegFnNameParts[1] = "descriptor_reg"; 3802 llvm::transform(Devices, std::next(RegFnNameParts.begin(), 2), 3803 [](const llvm::Triple &T) -> const std::string& { 3804 return T.getTriple(); 3805 }); 3806 llvm::sort(std::next(RegFnNameParts.begin(), 2), RegFnNameParts.end()); 3807 std::string Descriptor = getName(RegFnNameParts); 3808 RegFn = CGM.CreateGlobalInitOrDestructFunction(FTy, Descriptor, FI); 3809 CGF.StartFunction(GlobalDecl(), C.VoidTy, RegFn, FI, FunctionArgList()); 3810 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_register_lib), Desc); 3811 // Create a variable to drive the registration and unregistration of the 3812 // descriptor, so we can reuse the logic that emits Ctors and Dtors. 3813 ImplicitParamDecl RegUnregVar(C, C.getTranslationUnitDecl(), 3814 SourceLocation(), nullptr, C.CharTy, 3815 ImplicitParamDecl::Other); 3816 CGM.getCXXABI().registerGlobalDtor(CGF, RegUnregVar, UnRegFn, Desc); 3817 CGF.FinishFunction(); 3818 } 3819 if (CGM.supportsCOMDAT()) { 3820 // It is sufficient to call registration function only once, so create a 3821 // COMDAT group for registration/unregistration functions and associated 3822 // data. That would reduce startup time and code size. Registration 3823 // function serves as a COMDAT group key. 3824 llvm::Comdat *ComdatKey = M.getOrInsertComdat(RegFn->getName()); 3825 RegFn->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage); 3826 RegFn->setVisibility(llvm::GlobalValue::HiddenVisibility); 3827 RegFn->setComdat(ComdatKey); 3828 UnRegFn->setComdat(ComdatKey); 3829 DeviceImages->setComdat(ComdatKey); 3830 Desc->setComdat(ComdatKey); 3831 } 3832 return RegFn; 3833 } 3834 3835 void CGOpenMPRuntime::createOffloadEntry( 3836 llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags, 3837 llvm::GlobalValue::LinkageTypes Linkage) { 3838 StringRef Name = Addr->getName(); 3839 llvm::Module &M = CGM.getModule(); 3840 llvm::LLVMContext &C = M.getContext(); 3841 3842 // Create constant string with the name. 3843 llvm::Constant *StrPtrInit = llvm::ConstantDataArray::getString(C, Name); 3844 3845 std::string StringName = getName({"omp_offloading", "entry_name"}); 3846 auto *Str = new llvm::GlobalVariable( 3847 M, StrPtrInit->getType(), /*isConstant=*/true, 3848 llvm::GlobalValue::InternalLinkage, StrPtrInit, StringName); 3849 Str->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3850 3851 llvm::Constant *Data[] = {llvm::ConstantExpr::getBitCast(ID, CGM.VoidPtrTy), 3852 llvm::ConstantExpr::getBitCast(Str, CGM.Int8PtrTy), 3853 llvm::ConstantInt::get(CGM.SizeTy, Size), 3854 llvm::ConstantInt::get(CGM.Int32Ty, Flags), 3855 llvm::ConstantInt::get(CGM.Int32Ty, 0)}; 3856 std::string EntryName = getName({"omp_offloading", "entry", ""}); 3857 llvm::GlobalVariable *Entry = createGlobalStruct( 3858 CGM, getTgtOffloadEntryQTy(), /*IsConstant=*/true, Data, 3859 Twine(EntryName).concat(Name), llvm::GlobalValue::WeakAnyLinkage); 3860 3861 // The entry has to be created in the section the linker expects it to be. 3862 std::string Section = getName({"omp_offloading", "entries"}); 3863 Entry->setSection(Section); 3864 } 3865 3866 void CGOpenMPRuntime::createOffloadEntriesAndInfoMetadata() { 3867 // Emit the offloading entries and metadata so that the device codegen side 3868 // can easily figure out what to emit. The produced metadata looks like 3869 // this: 3870 // 3871 // !omp_offload.info = !{!1, ...} 3872 // 3873 // Right now we only generate metadata for function that contain target 3874 // regions. 3875 3876 // If we do not have entries, we don't need to do anything. 3877 if (OffloadEntriesInfoManager.empty()) 3878 return; 3879 3880 llvm::Module &M = CGM.getModule(); 3881 llvm::LLVMContext &C = M.getContext(); 3882 SmallVector<const OffloadEntriesInfoManagerTy::OffloadEntryInfo *, 16> 3883 OrderedEntries(OffloadEntriesInfoManager.size()); 3884 3885 // Auxiliary methods to create metadata values and strings. 3886 auto &&GetMDInt = [this](unsigned V) { 3887 return llvm::ConstantAsMetadata::get( 3888 llvm::ConstantInt::get(CGM.Int32Ty, V)); 3889 }; 3890 3891 auto &&GetMDString = [&C](StringRef V) { return llvm::MDString::get(C, V); }; 3892 3893 // Create the offloading info metadata node. 3894 llvm::NamedMDNode *MD = M.getOrInsertNamedMetadata("omp_offload.info"); 3895 3896 // Create function that emits metadata for each target region entry; 3897 auto &&TargetRegionMetadataEmitter = 3898 [&C, MD, &OrderedEntries, &GetMDInt, &GetMDString]( 3899 unsigned DeviceID, unsigned FileID, StringRef ParentName, 3900 unsigned Line, 3901 const OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion &E) { 3902 // Generate metadata for target regions. Each entry of this metadata 3903 // contains: 3904 // - Entry 0 -> Kind of this type of metadata (0). 3905 // - Entry 1 -> Device ID of the file where the entry was identified. 3906 // - Entry 2 -> File ID of the file where the entry was identified. 3907 // - Entry 3 -> Mangled name of the function where the entry was 3908 // identified. 3909 // - Entry 4 -> Line in the file where the entry was identified. 3910 // - Entry 5 -> Order the entry was created. 3911 // The first element of the metadata node is the kind. 3912 llvm::Metadata *Ops[] = {GetMDInt(E.getKind()), GetMDInt(DeviceID), 3913 GetMDInt(FileID), GetMDString(ParentName), 3914 GetMDInt(Line), GetMDInt(E.getOrder())}; 3915 3916 // Save this entry in the right position of the ordered entries array. 3917 OrderedEntries[E.getOrder()] = &E; 3918 3919 // Add metadata to the named metadata node. 3920 MD->addOperand(llvm::MDNode::get(C, Ops)); 3921 }; 3922 3923 OffloadEntriesInfoManager.actOnTargetRegionEntriesInfo( 3924 TargetRegionMetadataEmitter); 3925 3926 // Create function that emits metadata for each device global variable entry; 3927 auto &&DeviceGlobalVarMetadataEmitter = 3928 [&C, &OrderedEntries, &GetMDInt, &GetMDString, 3929 MD](StringRef MangledName, 3930 const OffloadEntriesInfoManagerTy::OffloadEntryInfoDeviceGlobalVar 3931 &E) { 3932 // Generate metadata for global variables. Each entry of this metadata 3933 // contains: 3934 // - Entry 0 -> Kind of this type of metadata (1). 3935 // - Entry 1 -> Mangled name of the variable. 3936 // - Entry 2 -> Declare target kind. 3937 // - Entry 3 -> Order the entry was created. 3938 // The first element of the metadata node is the kind. 3939 llvm::Metadata *Ops[] = { 3940 GetMDInt(E.getKind()), GetMDString(MangledName), 3941 GetMDInt(E.getFlags()), GetMDInt(E.getOrder())}; 3942 3943 // Save this entry in the right position of the ordered entries array. 3944 OrderedEntries[E.getOrder()] = &E; 3945 3946 // Add metadata to the named metadata node. 3947 MD->addOperand(llvm::MDNode::get(C, Ops)); 3948 }; 3949 3950 OffloadEntriesInfoManager.actOnDeviceGlobalVarEntriesInfo( 3951 DeviceGlobalVarMetadataEmitter); 3952 3953 for (const auto *E : OrderedEntries) { 3954 assert(E && "All ordered entries must exist!"); 3955 if (const auto *CE = 3956 dyn_cast<OffloadEntriesInfoManagerTy::OffloadEntryInfoTargetRegion>( 3957 E)) { 3958 if (!CE->getID() || !CE->getAddress()) { 3959 unsigned DiagID = CGM.getDiags().getCustomDiagID( 3960 DiagnosticsEngine::Error, 3961 "Offloading entry for target region is incorrect: either the " 3962 "address or the ID is invalid."); 3963 CGM.getDiags().Report(DiagID); 3964 continue; 3965 } 3966 createOffloadEntry(CE->getID(), CE->getAddress(), /*Size=*/0, 3967 CE->getFlags(), llvm::GlobalValue::WeakAnyLinkage); 3968 } else if (const auto *CE = 3969 dyn_cast<OffloadEntriesInfoManagerTy:: 3970 OffloadEntryInfoDeviceGlobalVar>(E)) { 3971 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags = 3972 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>( 3973 CE->getFlags()); 3974 switch (Flags) { 3975 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo: { 3976 if (!CE->getAddress()) { 3977 unsigned DiagID = CGM.getDiags().getCustomDiagID( 3978 DiagnosticsEngine::Error, 3979 "Offloading entry for declare target variable is incorrect: the " 3980 "address is invalid."); 3981 CGM.getDiags().Report(DiagID); 3982 continue; 3983 } 3984 // The vaiable has no definition - no need to add the entry. 3985 if (CE->getVarSize().isZero()) 3986 continue; 3987 break; 3988 } 3989 case OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink: 3990 assert(((CGM.getLangOpts().OpenMPIsDevice && !CE->getAddress()) || 3991 (!CGM.getLangOpts().OpenMPIsDevice && CE->getAddress())) && 3992 "Declaret target link address is set."); 3993 if (CGM.getLangOpts().OpenMPIsDevice) 3994 continue; 3995 if (!CE->getAddress()) { 3996 unsigned DiagID = CGM.getDiags().getCustomDiagID( 3997 DiagnosticsEngine::Error, 3998 "Offloading entry for declare target variable is incorrect: the " 3999 "address is invalid."); 4000 CGM.getDiags().Report(DiagID); 4001 continue; 4002 } 4003 break; 4004 } 4005 createOffloadEntry(CE->getAddress(), CE->getAddress(), 4006 CE->getVarSize().getQuantity(), Flags, 4007 CE->getLinkage()); 4008 } else { 4009 llvm_unreachable("Unsupported entry kind."); 4010 } 4011 } 4012 } 4013 4014 /// Loads all the offload entries information from the host IR 4015 /// metadata. 4016 void CGOpenMPRuntime::loadOffloadInfoMetadata() { 4017 // If we are in target mode, load the metadata from the host IR. This code has 4018 // to match the metadaata creation in createOffloadEntriesAndInfoMetadata(). 4019 4020 if (!CGM.getLangOpts().OpenMPIsDevice) 4021 return; 4022 4023 if (CGM.getLangOpts().OMPHostIRFile.empty()) 4024 return; 4025 4026 auto Buf = llvm::MemoryBuffer::getFile(CGM.getLangOpts().OMPHostIRFile); 4027 if (auto EC = Buf.getError()) { 4028 CGM.getDiags().Report(diag::err_cannot_open_file) 4029 << CGM.getLangOpts().OMPHostIRFile << EC.message(); 4030 return; 4031 } 4032 4033 llvm::LLVMContext C; 4034 auto ME = expectedToErrorOrAndEmitErrors( 4035 C, llvm::parseBitcodeFile(Buf.get()->getMemBufferRef(), C)); 4036 4037 if (auto EC = ME.getError()) { 4038 unsigned DiagID = CGM.getDiags().getCustomDiagID( 4039 DiagnosticsEngine::Error, "Unable to parse host IR file '%0':'%1'"); 4040 CGM.getDiags().Report(DiagID) 4041 << CGM.getLangOpts().OMPHostIRFile << EC.message(); 4042 return; 4043 } 4044 4045 llvm::NamedMDNode *MD = ME.get()->getNamedMetadata("omp_offload.info"); 4046 if (!MD) 4047 return; 4048 4049 for (llvm::MDNode *MN : MD->operands()) { 4050 auto &&GetMDInt = [MN](unsigned Idx) { 4051 auto *V = cast<llvm::ConstantAsMetadata>(MN->getOperand(Idx)); 4052 return cast<llvm::ConstantInt>(V->getValue())->getZExtValue(); 4053 }; 4054 4055 auto &&GetMDString = [MN](unsigned Idx) { 4056 auto *V = cast<llvm::MDString>(MN->getOperand(Idx)); 4057 return V->getString(); 4058 }; 4059 4060 switch (GetMDInt(0)) { 4061 default: 4062 llvm_unreachable("Unexpected metadata!"); 4063 break; 4064 case OffloadEntriesInfoManagerTy::OffloadEntryInfo:: 4065 OffloadingEntryInfoTargetRegion: 4066 OffloadEntriesInfoManager.initializeTargetRegionEntryInfo( 4067 /*DeviceID=*/GetMDInt(1), /*FileID=*/GetMDInt(2), 4068 /*ParentName=*/GetMDString(3), /*Line=*/GetMDInt(4), 4069 /*Order=*/GetMDInt(5)); 4070 break; 4071 case OffloadEntriesInfoManagerTy::OffloadEntryInfo:: 4072 OffloadingEntryInfoDeviceGlobalVar: 4073 OffloadEntriesInfoManager.initializeDeviceGlobalVarEntryInfo( 4074 /*MangledName=*/GetMDString(1), 4075 static_cast<OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind>( 4076 /*Flags=*/GetMDInt(2)), 4077 /*Order=*/GetMDInt(3)); 4078 break; 4079 } 4080 } 4081 } 4082 4083 void CGOpenMPRuntime::emitKmpRoutineEntryT(QualType KmpInt32Ty) { 4084 if (!KmpRoutineEntryPtrTy) { 4085 // Build typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); type. 4086 ASTContext &C = CGM.getContext(); 4087 QualType KmpRoutineEntryTyArgs[] = {KmpInt32Ty, C.VoidPtrTy}; 4088 FunctionProtoType::ExtProtoInfo EPI; 4089 KmpRoutineEntryPtrQTy = C.getPointerType( 4090 C.getFunctionType(KmpInt32Ty, KmpRoutineEntryTyArgs, EPI)); 4091 KmpRoutineEntryPtrTy = CGM.getTypes().ConvertType(KmpRoutineEntryPtrQTy); 4092 } 4093 } 4094 4095 QualType CGOpenMPRuntime::getTgtOffloadEntryQTy() { 4096 // Make sure the type of the entry is already created. This is the type we 4097 // have to create: 4098 // struct __tgt_offload_entry{ 4099 // void *addr; // Pointer to the offload entry info. 4100 // // (function or global) 4101 // char *name; // Name of the function or global. 4102 // size_t size; // Size of the entry info (0 if it a function). 4103 // int32_t flags; // Flags associated with the entry, e.g. 'link'. 4104 // int32_t reserved; // Reserved, to use by the runtime library. 4105 // }; 4106 if (TgtOffloadEntryQTy.isNull()) { 4107 ASTContext &C = CGM.getContext(); 4108 RecordDecl *RD = C.buildImplicitRecord("__tgt_offload_entry"); 4109 RD->startDefinition(); 4110 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4111 addFieldToRecordDecl(C, RD, C.getPointerType(C.CharTy)); 4112 addFieldToRecordDecl(C, RD, C.getSizeType()); 4113 addFieldToRecordDecl( 4114 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true)); 4115 addFieldToRecordDecl( 4116 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true)); 4117 RD->completeDefinition(); 4118 RD->addAttr(PackedAttr::CreateImplicit(C)); 4119 TgtOffloadEntryQTy = C.getRecordType(RD); 4120 } 4121 return TgtOffloadEntryQTy; 4122 } 4123 4124 QualType CGOpenMPRuntime::getTgtDeviceImageQTy() { 4125 // These are the types we need to build: 4126 // struct __tgt_device_image{ 4127 // void *ImageStart; // Pointer to the target code start. 4128 // void *ImageEnd; // Pointer to the target code end. 4129 // // We also add the host entries to the device image, as it may be useful 4130 // // for the target runtime to have access to that information. 4131 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all 4132 // // the entries. 4133 // __tgt_offload_entry *EntriesEnd; // End of the table with all the 4134 // // entries (non inclusive). 4135 // }; 4136 if (TgtDeviceImageQTy.isNull()) { 4137 ASTContext &C = CGM.getContext(); 4138 RecordDecl *RD = C.buildImplicitRecord("__tgt_device_image"); 4139 RD->startDefinition(); 4140 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4141 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4142 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4143 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4144 RD->completeDefinition(); 4145 TgtDeviceImageQTy = C.getRecordType(RD); 4146 } 4147 return TgtDeviceImageQTy; 4148 } 4149 4150 QualType CGOpenMPRuntime::getTgtBinaryDescriptorQTy() { 4151 // struct __tgt_bin_desc{ 4152 // int32_t NumDevices; // Number of devices supported. 4153 // __tgt_device_image *DeviceImages; // Arrays of device images 4154 // // (one per device). 4155 // __tgt_offload_entry *EntriesBegin; // Begin of the table with all the 4156 // // entries. 4157 // __tgt_offload_entry *EntriesEnd; // End of the table with all the 4158 // // entries (non inclusive). 4159 // }; 4160 if (TgtBinaryDescriptorQTy.isNull()) { 4161 ASTContext &C = CGM.getContext(); 4162 RecordDecl *RD = C.buildImplicitRecord("__tgt_bin_desc"); 4163 RD->startDefinition(); 4164 addFieldToRecordDecl( 4165 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/true)); 4166 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtDeviceImageQTy())); 4167 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4168 addFieldToRecordDecl(C, RD, C.getPointerType(getTgtOffloadEntryQTy())); 4169 RD->completeDefinition(); 4170 TgtBinaryDescriptorQTy = C.getRecordType(RD); 4171 } 4172 return TgtBinaryDescriptorQTy; 4173 } 4174 4175 namespace { 4176 struct PrivateHelpersTy { 4177 PrivateHelpersTy(const VarDecl *Original, const VarDecl *PrivateCopy, 4178 const VarDecl *PrivateElemInit) 4179 : Original(Original), PrivateCopy(PrivateCopy), 4180 PrivateElemInit(PrivateElemInit) {} 4181 const VarDecl *Original; 4182 const VarDecl *PrivateCopy; 4183 const VarDecl *PrivateElemInit; 4184 }; 4185 typedef std::pair<CharUnits /*Align*/, PrivateHelpersTy> PrivateDataTy; 4186 } // anonymous namespace 4187 4188 static RecordDecl * 4189 createPrivatesRecordDecl(CodeGenModule &CGM, ArrayRef<PrivateDataTy> Privates) { 4190 if (!Privates.empty()) { 4191 ASTContext &C = CGM.getContext(); 4192 // Build struct .kmp_privates_t. { 4193 // /* private vars */ 4194 // }; 4195 RecordDecl *RD = C.buildImplicitRecord(".kmp_privates.t"); 4196 RD->startDefinition(); 4197 for (const auto &Pair : Privates) { 4198 const VarDecl *VD = Pair.second.Original; 4199 QualType Type = VD->getType().getNonReferenceType(); 4200 FieldDecl *FD = addFieldToRecordDecl(C, RD, Type); 4201 if (VD->hasAttrs()) { 4202 for (specific_attr_iterator<AlignedAttr> I(VD->getAttrs().begin()), 4203 E(VD->getAttrs().end()); 4204 I != E; ++I) 4205 FD->addAttr(*I); 4206 } 4207 } 4208 RD->completeDefinition(); 4209 return RD; 4210 } 4211 return nullptr; 4212 } 4213 4214 static RecordDecl * 4215 createKmpTaskTRecordDecl(CodeGenModule &CGM, OpenMPDirectiveKind Kind, 4216 QualType KmpInt32Ty, 4217 QualType KmpRoutineEntryPointerQTy) { 4218 ASTContext &C = CGM.getContext(); 4219 // Build struct kmp_task_t { 4220 // void * shareds; 4221 // kmp_routine_entry_t routine; 4222 // kmp_int32 part_id; 4223 // kmp_cmplrdata_t data1; 4224 // kmp_cmplrdata_t data2; 4225 // For taskloops additional fields: 4226 // kmp_uint64 lb; 4227 // kmp_uint64 ub; 4228 // kmp_int64 st; 4229 // kmp_int32 liter; 4230 // void * reductions; 4231 // }; 4232 RecordDecl *UD = C.buildImplicitRecord("kmp_cmplrdata_t", TTK_Union); 4233 UD->startDefinition(); 4234 addFieldToRecordDecl(C, UD, KmpInt32Ty); 4235 addFieldToRecordDecl(C, UD, KmpRoutineEntryPointerQTy); 4236 UD->completeDefinition(); 4237 QualType KmpCmplrdataTy = C.getRecordType(UD); 4238 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t"); 4239 RD->startDefinition(); 4240 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4241 addFieldToRecordDecl(C, RD, KmpRoutineEntryPointerQTy); 4242 addFieldToRecordDecl(C, RD, KmpInt32Ty); 4243 addFieldToRecordDecl(C, RD, KmpCmplrdataTy); 4244 addFieldToRecordDecl(C, RD, KmpCmplrdataTy); 4245 if (isOpenMPTaskLoopDirective(Kind)) { 4246 QualType KmpUInt64Ty = 4247 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4248 QualType KmpInt64Ty = 4249 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4250 addFieldToRecordDecl(C, RD, KmpUInt64Ty); 4251 addFieldToRecordDecl(C, RD, KmpUInt64Ty); 4252 addFieldToRecordDecl(C, RD, KmpInt64Ty); 4253 addFieldToRecordDecl(C, RD, KmpInt32Ty); 4254 addFieldToRecordDecl(C, RD, C.VoidPtrTy); 4255 } 4256 RD->completeDefinition(); 4257 return RD; 4258 } 4259 4260 static RecordDecl * 4261 createKmpTaskTWithPrivatesRecordDecl(CodeGenModule &CGM, QualType KmpTaskTQTy, 4262 ArrayRef<PrivateDataTy> Privates) { 4263 ASTContext &C = CGM.getContext(); 4264 // Build struct kmp_task_t_with_privates { 4265 // kmp_task_t task_data; 4266 // .kmp_privates_t. privates; 4267 // }; 4268 RecordDecl *RD = C.buildImplicitRecord("kmp_task_t_with_privates"); 4269 RD->startDefinition(); 4270 addFieldToRecordDecl(C, RD, KmpTaskTQTy); 4271 if (const RecordDecl *PrivateRD = createPrivatesRecordDecl(CGM, Privates)) 4272 addFieldToRecordDecl(C, RD, C.getRecordType(PrivateRD)); 4273 RD->completeDefinition(); 4274 return RD; 4275 } 4276 4277 /// Emit a proxy function which accepts kmp_task_t as the second 4278 /// argument. 4279 /// \code 4280 /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { 4281 /// TaskFunction(gtid, tt->part_id, &tt->privates, task_privates_map, tt, 4282 /// For taskloops: 4283 /// tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, 4284 /// tt->reductions, tt->shareds); 4285 /// return 0; 4286 /// } 4287 /// \endcode 4288 static llvm::Value * 4289 emitProxyTaskFunction(CodeGenModule &CGM, SourceLocation Loc, 4290 OpenMPDirectiveKind Kind, QualType KmpInt32Ty, 4291 QualType KmpTaskTWithPrivatesPtrQTy, 4292 QualType KmpTaskTWithPrivatesQTy, QualType KmpTaskTQTy, 4293 QualType SharedsPtrTy, llvm::Value *TaskFunction, 4294 llvm::Value *TaskPrivatesMap) { 4295 ASTContext &C = CGM.getContext(); 4296 FunctionArgList Args; 4297 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, 4298 ImplicitParamDecl::Other); 4299 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4300 KmpTaskTWithPrivatesPtrQTy.withRestrict(), 4301 ImplicitParamDecl::Other); 4302 Args.push_back(&GtidArg); 4303 Args.push_back(&TaskTypeArg); 4304 const auto &TaskEntryFnInfo = 4305 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); 4306 llvm::FunctionType *TaskEntryTy = 4307 CGM.getTypes().GetFunctionType(TaskEntryFnInfo); 4308 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_entry", ""}); 4309 auto *TaskEntry = llvm::Function::Create( 4310 TaskEntryTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); 4311 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskEntry, TaskEntryFnInfo); 4312 TaskEntry->setDoesNotRecurse(); 4313 CodeGenFunction CGF(CGM); 4314 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, TaskEntry, TaskEntryFnInfo, Args, 4315 Loc, Loc); 4316 4317 // TaskFunction(gtid, tt->task_data.part_id, &tt->privates, task_privates_map, 4318 // tt, 4319 // For taskloops: 4320 // tt->task_data.lb, tt->task_data.ub, tt->task_data.st, tt->task_data.liter, 4321 // tt->task_data.shareds); 4322 llvm::Value *GtidParam = CGF.EmitLoadOfScalar( 4323 CGF.GetAddrOfLocalVar(&GtidArg), /*Volatile=*/false, KmpInt32Ty, Loc); 4324 LValue TDBase = CGF.EmitLoadOfPointerLValue( 4325 CGF.GetAddrOfLocalVar(&TaskTypeArg), 4326 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4327 const auto *KmpTaskTWithPrivatesQTyRD = 4328 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); 4329 LValue Base = 4330 CGF.EmitLValueForField(TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); 4331 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); 4332 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); 4333 LValue PartIdLVal = CGF.EmitLValueForField(Base, *PartIdFI); 4334 llvm::Value *PartidParam = PartIdLVal.getPointer(); 4335 4336 auto SharedsFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTShareds); 4337 LValue SharedsLVal = CGF.EmitLValueForField(Base, *SharedsFI); 4338 llvm::Value *SharedsParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4339 CGF.EmitLoadOfScalar(SharedsLVal, Loc), 4340 CGF.ConvertTypeForMem(SharedsPtrTy)); 4341 4342 auto PrivatesFI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1); 4343 llvm::Value *PrivatesParam; 4344 if (PrivatesFI != KmpTaskTWithPrivatesQTyRD->field_end()) { 4345 LValue PrivatesLVal = CGF.EmitLValueForField(TDBase, *PrivatesFI); 4346 PrivatesParam = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4347 PrivatesLVal.getPointer(), CGF.VoidPtrTy); 4348 } else { 4349 PrivatesParam = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 4350 } 4351 4352 llvm::Value *CommonArgs[] = {GtidParam, PartidParam, PrivatesParam, 4353 TaskPrivatesMap, 4354 CGF.Builder 4355 .CreatePointerBitCastOrAddrSpaceCast( 4356 TDBase.getAddress(), CGF.VoidPtrTy) 4357 .getPointer()}; 4358 SmallVector<llvm::Value *, 16> CallArgs(std::begin(CommonArgs), 4359 std::end(CommonArgs)); 4360 if (isOpenMPTaskLoopDirective(Kind)) { 4361 auto LBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound); 4362 LValue LBLVal = CGF.EmitLValueForField(Base, *LBFI); 4363 llvm::Value *LBParam = CGF.EmitLoadOfScalar(LBLVal, Loc); 4364 auto UBFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound); 4365 LValue UBLVal = CGF.EmitLValueForField(Base, *UBFI); 4366 llvm::Value *UBParam = CGF.EmitLoadOfScalar(UBLVal, Loc); 4367 auto StFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTStride); 4368 LValue StLVal = CGF.EmitLValueForField(Base, *StFI); 4369 llvm::Value *StParam = CGF.EmitLoadOfScalar(StLVal, Loc); 4370 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); 4371 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); 4372 llvm::Value *LIParam = CGF.EmitLoadOfScalar(LILVal, Loc); 4373 auto RFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTReductions); 4374 LValue RLVal = CGF.EmitLValueForField(Base, *RFI); 4375 llvm::Value *RParam = CGF.EmitLoadOfScalar(RLVal, Loc); 4376 CallArgs.push_back(LBParam); 4377 CallArgs.push_back(UBParam); 4378 CallArgs.push_back(StParam); 4379 CallArgs.push_back(LIParam); 4380 CallArgs.push_back(RParam); 4381 } 4382 CallArgs.push_back(SharedsParam); 4383 4384 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskFunction, 4385 CallArgs); 4386 CGF.EmitStoreThroughLValue(RValue::get(CGF.Builder.getInt32(/*C=*/0)), 4387 CGF.MakeAddrLValue(CGF.ReturnValue, KmpInt32Ty)); 4388 CGF.FinishFunction(); 4389 return TaskEntry; 4390 } 4391 4392 static llvm::Value *emitDestructorsFunction(CodeGenModule &CGM, 4393 SourceLocation Loc, 4394 QualType KmpInt32Ty, 4395 QualType KmpTaskTWithPrivatesPtrQTy, 4396 QualType KmpTaskTWithPrivatesQTy) { 4397 ASTContext &C = CGM.getContext(); 4398 FunctionArgList Args; 4399 ImplicitParamDecl GtidArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, KmpInt32Ty, 4400 ImplicitParamDecl::Other); 4401 ImplicitParamDecl TaskTypeArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4402 KmpTaskTWithPrivatesPtrQTy.withRestrict(), 4403 ImplicitParamDecl::Other); 4404 Args.push_back(&GtidArg); 4405 Args.push_back(&TaskTypeArg); 4406 const auto &DestructorFnInfo = 4407 CGM.getTypes().arrangeBuiltinFunctionDeclaration(KmpInt32Ty, Args); 4408 llvm::FunctionType *DestructorFnTy = 4409 CGM.getTypes().GetFunctionType(DestructorFnInfo); 4410 std::string Name = 4411 CGM.getOpenMPRuntime().getName({"omp_task_destructor", ""}); 4412 auto *DestructorFn = 4413 llvm::Function::Create(DestructorFnTy, llvm::GlobalValue::InternalLinkage, 4414 Name, &CGM.getModule()); 4415 CGM.SetInternalFunctionAttributes(GlobalDecl(), DestructorFn, 4416 DestructorFnInfo); 4417 DestructorFn->setDoesNotRecurse(); 4418 CodeGenFunction CGF(CGM); 4419 CGF.StartFunction(GlobalDecl(), KmpInt32Ty, DestructorFn, DestructorFnInfo, 4420 Args, Loc, Loc); 4421 4422 LValue Base = CGF.EmitLoadOfPointerLValue( 4423 CGF.GetAddrOfLocalVar(&TaskTypeArg), 4424 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4425 const auto *KmpTaskTWithPrivatesQTyRD = 4426 cast<RecordDecl>(KmpTaskTWithPrivatesQTy->getAsTagDecl()); 4427 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); 4428 Base = CGF.EmitLValueForField(Base, *FI); 4429 for (const auto *Field : 4430 cast<RecordDecl>(FI->getType()->getAsTagDecl())->fields()) { 4431 if (QualType::DestructionKind DtorKind = 4432 Field->getType().isDestructedType()) { 4433 LValue FieldLValue = CGF.EmitLValueForField(Base, Field); 4434 CGF.pushDestroy(DtorKind, FieldLValue.getAddress(), Field->getType()); 4435 } 4436 } 4437 CGF.FinishFunction(); 4438 return DestructorFn; 4439 } 4440 4441 /// Emit a privates mapping function for correct handling of private and 4442 /// firstprivate variables. 4443 /// \code 4444 /// void .omp_task_privates_map.(const .privates. *noalias privs, <ty1> 4445 /// **noalias priv1,..., <tyn> **noalias privn) { 4446 /// *priv1 = &.privates.priv1; 4447 /// ...; 4448 /// *privn = &.privates.privn; 4449 /// } 4450 /// \endcode 4451 static llvm::Value * 4452 emitTaskPrivateMappingFunction(CodeGenModule &CGM, SourceLocation Loc, 4453 ArrayRef<const Expr *> PrivateVars, 4454 ArrayRef<const Expr *> FirstprivateVars, 4455 ArrayRef<const Expr *> LastprivateVars, 4456 QualType PrivatesQTy, 4457 ArrayRef<PrivateDataTy> Privates) { 4458 ASTContext &C = CGM.getContext(); 4459 FunctionArgList Args; 4460 ImplicitParamDecl TaskPrivatesArg( 4461 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4462 C.getPointerType(PrivatesQTy).withConst().withRestrict(), 4463 ImplicitParamDecl::Other); 4464 Args.push_back(&TaskPrivatesArg); 4465 llvm::DenseMap<const VarDecl *, unsigned> PrivateVarsPos; 4466 unsigned Counter = 1; 4467 for (const Expr *E : PrivateVars) { 4468 Args.push_back(ImplicitParamDecl::Create( 4469 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4470 C.getPointerType(C.getPointerType(E->getType())) 4471 .withConst() 4472 .withRestrict(), 4473 ImplicitParamDecl::Other)); 4474 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4475 PrivateVarsPos[VD] = Counter; 4476 ++Counter; 4477 } 4478 for (const Expr *E : FirstprivateVars) { 4479 Args.push_back(ImplicitParamDecl::Create( 4480 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4481 C.getPointerType(C.getPointerType(E->getType())) 4482 .withConst() 4483 .withRestrict(), 4484 ImplicitParamDecl::Other)); 4485 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4486 PrivateVarsPos[VD] = Counter; 4487 ++Counter; 4488 } 4489 for (const Expr *E : LastprivateVars) { 4490 Args.push_back(ImplicitParamDecl::Create( 4491 C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4492 C.getPointerType(C.getPointerType(E->getType())) 4493 .withConst() 4494 .withRestrict(), 4495 ImplicitParamDecl::Other)); 4496 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4497 PrivateVarsPos[VD] = Counter; 4498 ++Counter; 4499 } 4500 const auto &TaskPrivatesMapFnInfo = 4501 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 4502 llvm::FunctionType *TaskPrivatesMapTy = 4503 CGM.getTypes().GetFunctionType(TaskPrivatesMapFnInfo); 4504 std::string Name = 4505 CGM.getOpenMPRuntime().getName({"omp_task_privates_map", ""}); 4506 auto *TaskPrivatesMap = llvm::Function::Create( 4507 TaskPrivatesMapTy, llvm::GlobalValue::InternalLinkage, Name, 4508 &CGM.getModule()); 4509 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskPrivatesMap, 4510 TaskPrivatesMapFnInfo); 4511 TaskPrivatesMap->removeFnAttr(llvm::Attribute::NoInline); 4512 TaskPrivatesMap->removeFnAttr(llvm::Attribute::OptimizeNone); 4513 TaskPrivatesMap->addFnAttr(llvm::Attribute::AlwaysInline); 4514 CodeGenFunction CGF(CGM); 4515 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskPrivatesMap, 4516 TaskPrivatesMapFnInfo, Args, Loc, Loc); 4517 4518 // *privi = &.privates.privi; 4519 LValue Base = CGF.EmitLoadOfPointerLValue( 4520 CGF.GetAddrOfLocalVar(&TaskPrivatesArg), 4521 TaskPrivatesArg.getType()->castAs<PointerType>()); 4522 const auto *PrivatesQTyRD = cast<RecordDecl>(PrivatesQTy->getAsTagDecl()); 4523 Counter = 0; 4524 for (const FieldDecl *Field : PrivatesQTyRD->fields()) { 4525 LValue FieldLVal = CGF.EmitLValueForField(Base, Field); 4526 const VarDecl *VD = Args[PrivateVarsPos[Privates[Counter].second.Original]]; 4527 LValue RefLVal = 4528 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(VD), VD->getType()); 4529 LValue RefLoadLVal = CGF.EmitLoadOfPointerLValue( 4530 RefLVal.getAddress(), RefLVal.getType()->castAs<PointerType>()); 4531 CGF.EmitStoreOfScalar(FieldLVal.getPointer(), RefLoadLVal); 4532 ++Counter; 4533 } 4534 CGF.FinishFunction(); 4535 return TaskPrivatesMap; 4536 } 4537 4538 static bool stable_sort_comparator(const PrivateDataTy P1, 4539 const PrivateDataTy P2) { 4540 return P1.first > P2.first; 4541 } 4542 4543 /// Emit initialization for private variables in task-based directives. 4544 static void emitPrivatesInit(CodeGenFunction &CGF, 4545 const OMPExecutableDirective &D, 4546 Address KmpTaskSharedsPtr, LValue TDBase, 4547 const RecordDecl *KmpTaskTWithPrivatesQTyRD, 4548 QualType SharedsTy, QualType SharedsPtrTy, 4549 const OMPTaskDataTy &Data, 4550 ArrayRef<PrivateDataTy> Privates, bool ForDup) { 4551 ASTContext &C = CGF.getContext(); 4552 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); 4553 LValue PrivatesBase = CGF.EmitLValueForField(TDBase, *FI); 4554 OpenMPDirectiveKind Kind = isOpenMPTaskLoopDirective(D.getDirectiveKind()) 4555 ? OMPD_taskloop 4556 : OMPD_task; 4557 const CapturedStmt &CS = *D.getCapturedStmt(Kind); 4558 CodeGenFunction::CGCapturedStmtInfo CapturesInfo(CS); 4559 LValue SrcBase; 4560 bool IsTargetTask = 4561 isOpenMPTargetDataManagementDirective(D.getDirectiveKind()) || 4562 isOpenMPTargetExecutionDirective(D.getDirectiveKind()); 4563 // For target-based directives skip 3 firstprivate arrays BasePointersArray, 4564 // PointersArray and SizesArray. The original variables for these arrays are 4565 // not captured and we get their addresses explicitly. 4566 if ((!IsTargetTask && !Data.FirstprivateVars.empty()) || 4567 (IsTargetTask && KmpTaskSharedsPtr.isValid())) { 4568 SrcBase = CGF.MakeAddrLValue( 4569 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4570 KmpTaskSharedsPtr, CGF.ConvertTypeForMem(SharedsPtrTy)), 4571 SharedsTy); 4572 } 4573 FI = cast<RecordDecl>(FI->getType()->getAsTagDecl())->field_begin(); 4574 for (const PrivateDataTy &Pair : Privates) { 4575 const VarDecl *VD = Pair.second.PrivateCopy; 4576 const Expr *Init = VD->getAnyInitializer(); 4577 if (Init && (!ForDup || (isa<CXXConstructExpr>(Init) && 4578 !CGF.isTrivialInitializer(Init)))) { 4579 LValue PrivateLValue = CGF.EmitLValueForField(PrivatesBase, *FI); 4580 if (const VarDecl *Elem = Pair.second.PrivateElemInit) { 4581 const VarDecl *OriginalVD = Pair.second.Original; 4582 // Check if the variable is the target-based BasePointersArray, 4583 // PointersArray or SizesArray. 4584 LValue SharedRefLValue; 4585 QualType Type = OriginalVD->getType(); 4586 const FieldDecl *SharedField = CapturesInfo.lookup(OriginalVD); 4587 if (IsTargetTask && !SharedField) { 4588 assert(isa<ImplicitParamDecl>(OriginalVD) && 4589 isa<CapturedDecl>(OriginalVD->getDeclContext()) && 4590 cast<CapturedDecl>(OriginalVD->getDeclContext()) 4591 ->getNumParams() == 0 && 4592 isa<TranslationUnitDecl>( 4593 cast<CapturedDecl>(OriginalVD->getDeclContext()) 4594 ->getDeclContext()) && 4595 "Expected artificial target data variable."); 4596 SharedRefLValue = 4597 CGF.MakeAddrLValue(CGF.GetAddrOfLocalVar(OriginalVD), Type); 4598 } else { 4599 SharedRefLValue = CGF.EmitLValueForField(SrcBase, SharedField); 4600 SharedRefLValue = CGF.MakeAddrLValue( 4601 Address(SharedRefLValue.getPointer(), C.getDeclAlign(OriginalVD)), 4602 SharedRefLValue.getType(), LValueBaseInfo(AlignmentSource::Decl), 4603 SharedRefLValue.getTBAAInfo()); 4604 } 4605 if (Type->isArrayType()) { 4606 // Initialize firstprivate array. 4607 if (!isa<CXXConstructExpr>(Init) || CGF.isTrivialInitializer(Init)) { 4608 // Perform simple memcpy. 4609 CGF.EmitAggregateAssign(PrivateLValue, SharedRefLValue, Type); 4610 } else { 4611 // Initialize firstprivate array using element-by-element 4612 // initialization. 4613 CGF.EmitOMPAggregateAssign( 4614 PrivateLValue.getAddress(), SharedRefLValue.getAddress(), Type, 4615 [&CGF, Elem, Init, &CapturesInfo](Address DestElement, 4616 Address SrcElement) { 4617 // Clean up any temporaries needed by the initialization. 4618 CodeGenFunction::OMPPrivateScope InitScope(CGF); 4619 InitScope.addPrivate( 4620 Elem, [SrcElement]() -> Address { return SrcElement; }); 4621 (void)InitScope.Privatize(); 4622 // Emit initialization for single element. 4623 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII( 4624 CGF, &CapturesInfo); 4625 CGF.EmitAnyExprToMem(Init, DestElement, 4626 Init->getType().getQualifiers(), 4627 /*IsInitializer=*/false); 4628 }); 4629 } 4630 } else { 4631 CodeGenFunction::OMPPrivateScope InitScope(CGF); 4632 InitScope.addPrivate(Elem, [SharedRefLValue]() -> Address { 4633 return SharedRefLValue.getAddress(); 4634 }); 4635 (void)InitScope.Privatize(); 4636 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CapturesInfo); 4637 CGF.EmitExprAsInit(Init, VD, PrivateLValue, 4638 /*capturedByInit=*/false); 4639 } 4640 } else { 4641 CGF.EmitExprAsInit(Init, VD, PrivateLValue, /*capturedByInit=*/false); 4642 } 4643 } 4644 ++FI; 4645 } 4646 } 4647 4648 /// Check if duplication function is required for taskloops. 4649 static bool checkInitIsRequired(CodeGenFunction &CGF, 4650 ArrayRef<PrivateDataTy> Privates) { 4651 bool InitRequired = false; 4652 for (const PrivateDataTy &Pair : Privates) { 4653 const VarDecl *VD = Pair.second.PrivateCopy; 4654 const Expr *Init = VD->getAnyInitializer(); 4655 InitRequired = InitRequired || (Init && isa<CXXConstructExpr>(Init) && 4656 !CGF.isTrivialInitializer(Init)); 4657 if (InitRequired) 4658 break; 4659 } 4660 return InitRequired; 4661 } 4662 4663 4664 /// Emit task_dup function (for initialization of 4665 /// private/firstprivate/lastprivate vars and last_iter flag) 4666 /// \code 4667 /// void __task_dup_entry(kmp_task_t *task_dst, const kmp_task_t *task_src, int 4668 /// lastpriv) { 4669 /// // setup lastprivate flag 4670 /// task_dst->last = lastpriv; 4671 /// // could be constructor calls here... 4672 /// } 4673 /// \endcode 4674 static llvm::Value * 4675 emitTaskDupFunction(CodeGenModule &CGM, SourceLocation Loc, 4676 const OMPExecutableDirective &D, 4677 QualType KmpTaskTWithPrivatesPtrQTy, 4678 const RecordDecl *KmpTaskTWithPrivatesQTyRD, 4679 const RecordDecl *KmpTaskTQTyRD, QualType SharedsTy, 4680 QualType SharedsPtrTy, const OMPTaskDataTy &Data, 4681 ArrayRef<PrivateDataTy> Privates, bool WithLastIter) { 4682 ASTContext &C = CGM.getContext(); 4683 FunctionArgList Args; 4684 ImplicitParamDecl DstArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4685 KmpTaskTWithPrivatesPtrQTy, 4686 ImplicitParamDecl::Other); 4687 ImplicitParamDecl SrcArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 4688 KmpTaskTWithPrivatesPtrQTy, 4689 ImplicitParamDecl::Other); 4690 ImplicitParamDecl LastprivArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.IntTy, 4691 ImplicitParamDecl::Other); 4692 Args.push_back(&DstArg); 4693 Args.push_back(&SrcArg); 4694 Args.push_back(&LastprivArg); 4695 const auto &TaskDupFnInfo = 4696 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 4697 llvm::FunctionType *TaskDupTy = CGM.getTypes().GetFunctionType(TaskDupFnInfo); 4698 std::string Name = CGM.getOpenMPRuntime().getName({"omp_task_dup", ""}); 4699 auto *TaskDup = llvm::Function::Create( 4700 TaskDupTy, llvm::GlobalValue::InternalLinkage, Name, &CGM.getModule()); 4701 CGM.SetInternalFunctionAttributes(GlobalDecl(), TaskDup, TaskDupFnInfo); 4702 TaskDup->setDoesNotRecurse(); 4703 CodeGenFunction CGF(CGM); 4704 CGF.StartFunction(GlobalDecl(), C.VoidTy, TaskDup, TaskDupFnInfo, Args, Loc, 4705 Loc); 4706 4707 LValue TDBase = CGF.EmitLoadOfPointerLValue( 4708 CGF.GetAddrOfLocalVar(&DstArg), 4709 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4710 // task_dst->liter = lastpriv; 4711 if (WithLastIter) { 4712 auto LIFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTLastIter); 4713 LValue Base = CGF.EmitLValueForField( 4714 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); 4715 LValue LILVal = CGF.EmitLValueForField(Base, *LIFI); 4716 llvm::Value *Lastpriv = CGF.EmitLoadOfScalar( 4717 CGF.GetAddrOfLocalVar(&LastprivArg), /*Volatile=*/false, C.IntTy, Loc); 4718 CGF.EmitStoreOfScalar(Lastpriv, LILVal); 4719 } 4720 4721 // Emit initial values for private copies (if any). 4722 assert(!Privates.empty()); 4723 Address KmpTaskSharedsPtr = Address::invalid(); 4724 if (!Data.FirstprivateVars.empty()) { 4725 LValue TDBase = CGF.EmitLoadOfPointerLValue( 4726 CGF.GetAddrOfLocalVar(&SrcArg), 4727 KmpTaskTWithPrivatesPtrQTy->castAs<PointerType>()); 4728 LValue Base = CGF.EmitLValueForField( 4729 TDBase, *KmpTaskTWithPrivatesQTyRD->field_begin()); 4730 KmpTaskSharedsPtr = Address( 4731 CGF.EmitLoadOfScalar(CGF.EmitLValueForField( 4732 Base, *std::next(KmpTaskTQTyRD->field_begin(), 4733 KmpTaskTShareds)), 4734 Loc), 4735 CGF.getNaturalTypeAlignment(SharedsTy)); 4736 } 4737 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, TDBase, KmpTaskTWithPrivatesQTyRD, 4738 SharedsTy, SharedsPtrTy, Data, Privates, /*ForDup=*/true); 4739 CGF.FinishFunction(); 4740 return TaskDup; 4741 } 4742 4743 /// Checks if destructor function is required to be generated. 4744 /// \return true if cleanups are required, false otherwise. 4745 static bool 4746 checkDestructorsRequired(const RecordDecl *KmpTaskTWithPrivatesQTyRD) { 4747 bool NeedsCleanup = false; 4748 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin(), 1); 4749 const auto *PrivateRD = cast<RecordDecl>(FI->getType()->getAsTagDecl()); 4750 for (const FieldDecl *FD : PrivateRD->fields()) { 4751 NeedsCleanup = NeedsCleanup || FD->getType().isDestructedType(); 4752 if (NeedsCleanup) 4753 break; 4754 } 4755 return NeedsCleanup; 4756 } 4757 4758 CGOpenMPRuntime::TaskResultTy 4759 CGOpenMPRuntime::emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, 4760 const OMPExecutableDirective &D, 4761 llvm::Value *TaskFunction, QualType SharedsTy, 4762 Address Shareds, const OMPTaskDataTy &Data) { 4763 ASTContext &C = CGM.getContext(); 4764 llvm::SmallVector<PrivateDataTy, 4> Privates; 4765 // Aggregate privates and sort them by the alignment. 4766 auto I = Data.PrivateCopies.begin(); 4767 for (const Expr *E : Data.PrivateVars) { 4768 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4769 Privates.emplace_back( 4770 C.getDeclAlign(VD), 4771 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), 4772 /*PrivateElemInit=*/nullptr)); 4773 ++I; 4774 } 4775 I = Data.FirstprivateCopies.begin(); 4776 auto IElemInitRef = Data.FirstprivateInits.begin(); 4777 for (const Expr *E : Data.FirstprivateVars) { 4778 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4779 Privates.emplace_back( 4780 C.getDeclAlign(VD), 4781 PrivateHelpersTy( 4782 VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), 4783 cast<VarDecl>(cast<DeclRefExpr>(*IElemInitRef)->getDecl()))); 4784 ++I; 4785 ++IElemInitRef; 4786 } 4787 I = Data.LastprivateCopies.begin(); 4788 for (const Expr *E : Data.LastprivateVars) { 4789 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4790 Privates.emplace_back( 4791 C.getDeclAlign(VD), 4792 PrivateHelpersTy(VD, cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()), 4793 /*PrivateElemInit=*/nullptr)); 4794 ++I; 4795 } 4796 std::stable_sort(Privates.begin(), Privates.end(), stable_sort_comparator); 4797 QualType KmpInt32Ty = C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 4798 // Build type kmp_routine_entry_t (if not built yet). 4799 emitKmpRoutineEntryT(KmpInt32Ty); 4800 // Build type kmp_task_t (if not built yet). 4801 if (isOpenMPTaskLoopDirective(D.getDirectiveKind())) { 4802 if (SavedKmpTaskloopTQTy.isNull()) { 4803 SavedKmpTaskloopTQTy = C.getRecordType(createKmpTaskTRecordDecl( 4804 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); 4805 } 4806 KmpTaskTQTy = SavedKmpTaskloopTQTy; 4807 } else { 4808 assert((D.getDirectiveKind() == OMPD_task || 4809 isOpenMPTargetExecutionDirective(D.getDirectiveKind()) || 4810 isOpenMPTargetDataManagementDirective(D.getDirectiveKind())) && 4811 "Expected taskloop, task or target directive"); 4812 if (SavedKmpTaskTQTy.isNull()) { 4813 SavedKmpTaskTQTy = C.getRecordType(createKmpTaskTRecordDecl( 4814 CGM, D.getDirectiveKind(), KmpInt32Ty, KmpRoutineEntryPtrQTy)); 4815 } 4816 KmpTaskTQTy = SavedKmpTaskTQTy; 4817 } 4818 const auto *KmpTaskTQTyRD = cast<RecordDecl>(KmpTaskTQTy->getAsTagDecl()); 4819 // Build particular struct kmp_task_t for the given task. 4820 const RecordDecl *KmpTaskTWithPrivatesQTyRD = 4821 createKmpTaskTWithPrivatesRecordDecl(CGM, KmpTaskTQTy, Privates); 4822 QualType KmpTaskTWithPrivatesQTy = C.getRecordType(KmpTaskTWithPrivatesQTyRD); 4823 QualType KmpTaskTWithPrivatesPtrQTy = 4824 C.getPointerType(KmpTaskTWithPrivatesQTy); 4825 llvm::Type *KmpTaskTWithPrivatesTy = CGF.ConvertType(KmpTaskTWithPrivatesQTy); 4826 llvm::Type *KmpTaskTWithPrivatesPtrTy = 4827 KmpTaskTWithPrivatesTy->getPointerTo(); 4828 llvm::Value *KmpTaskTWithPrivatesTySize = 4829 CGF.getTypeSize(KmpTaskTWithPrivatesQTy); 4830 QualType SharedsPtrTy = C.getPointerType(SharedsTy); 4831 4832 // Emit initial values for private copies (if any). 4833 llvm::Value *TaskPrivatesMap = nullptr; 4834 llvm::Type *TaskPrivatesMapTy = 4835 std::next(cast<llvm::Function>(TaskFunction)->arg_begin(), 3)->getType(); 4836 if (!Privates.empty()) { 4837 auto FI = std::next(KmpTaskTWithPrivatesQTyRD->field_begin()); 4838 TaskPrivatesMap = emitTaskPrivateMappingFunction( 4839 CGM, Loc, Data.PrivateVars, Data.FirstprivateVars, Data.LastprivateVars, 4840 FI->getType(), Privates); 4841 TaskPrivatesMap = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4842 TaskPrivatesMap, TaskPrivatesMapTy); 4843 } else { 4844 TaskPrivatesMap = llvm::ConstantPointerNull::get( 4845 cast<llvm::PointerType>(TaskPrivatesMapTy)); 4846 } 4847 // Build a proxy function kmp_int32 .omp_task_entry.(kmp_int32 gtid, 4848 // kmp_task_t *tt); 4849 llvm::Value *TaskEntry = emitProxyTaskFunction( 4850 CGM, Loc, D.getDirectiveKind(), KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, 4851 KmpTaskTWithPrivatesQTy, KmpTaskTQTy, SharedsPtrTy, TaskFunction, 4852 TaskPrivatesMap); 4853 4854 // Build call kmp_task_t * __kmpc_omp_task_alloc(ident_t *, kmp_int32 gtid, 4855 // kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, 4856 // kmp_routine_entry_t *task_entry); 4857 // Task flags. Format is taken from 4858 // http://llvm.org/svn/llvm-project/openmp/trunk/runtime/src/kmp.h, 4859 // description of kmp_tasking_flags struct. 4860 enum { 4861 TiedFlag = 0x1, 4862 FinalFlag = 0x2, 4863 DestructorsFlag = 0x8, 4864 PriorityFlag = 0x20 4865 }; 4866 unsigned Flags = Data.Tied ? TiedFlag : 0; 4867 bool NeedsCleanup = false; 4868 if (!Privates.empty()) { 4869 NeedsCleanup = checkDestructorsRequired(KmpTaskTWithPrivatesQTyRD); 4870 if (NeedsCleanup) 4871 Flags = Flags | DestructorsFlag; 4872 } 4873 if (Data.Priority.getInt()) 4874 Flags = Flags | PriorityFlag; 4875 llvm::Value *TaskFlags = 4876 Data.Final.getPointer() 4877 ? CGF.Builder.CreateSelect(Data.Final.getPointer(), 4878 CGF.Builder.getInt32(FinalFlag), 4879 CGF.Builder.getInt32(/*C=*/0)) 4880 : CGF.Builder.getInt32(Data.Final.getInt() ? FinalFlag : 0); 4881 TaskFlags = CGF.Builder.CreateOr(TaskFlags, CGF.Builder.getInt32(Flags)); 4882 llvm::Value *SharedsSize = CGM.getSize(C.getTypeSizeInChars(SharedsTy)); 4883 llvm::Value *AllocArgs[] = {emitUpdateLocation(CGF, Loc), 4884 getThreadID(CGF, Loc), TaskFlags, 4885 KmpTaskTWithPrivatesTySize, SharedsSize, 4886 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4887 TaskEntry, KmpRoutineEntryPtrTy)}; 4888 llvm::Value *NewTask = CGF.EmitRuntimeCall( 4889 createRuntimeFunction(OMPRTL__kmpc_omp_task_alloc), AllocArgs); 4890 llvm::Value *NewTaskNewTaskTTy = 4891 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4892 NewTask, KmpTaskTWithPrivatesPtrTy); 4893 LValue Base = CGF.MakeNaturalAlignAddrLValue(NewTaskNewTaskTTy, 4894 KmpTaskTWithPrivatesQTy); 4895 LValue TDBase = 4896 CGF.EmitLValueForField(Base, *KmpTaskTWithPrivatesQTyRD->field_begin()); 4897 // Fill the data in the resulting kmp_task_t record. 4898 // Copy shareds if there are any. 4899 Address KmpTaskSharedsPtr = Address::invalid(); 4900 if (!SharedsTy->getAsStructureType()->getDecl()->field_empty()) { 4901 KmpTaskSharedsPtr = 4902 Address(CGF.EmitLoadOfScalar( 4903 CGF.EmitLValueForField( 4904 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), 4905 KmpTaskTShareds)), 4906 Loc), 4907 CGF.getNaturalTypeAlignment(SharedsTy)); 4908 LValue Dest = CGF.MakeAddrLValue(KmpTaskSharedsPtr, SharedsTy); 4909 LValue Src = CGF.MakeAddrLValue(Shareds, SharedsTy); 4910 CGF.EmitAggregateCopy(Dest, Src, SharedsTy, AggValueSlot::DoesNotOverlap); 4911 } 4912 // Emit initial values for private copies (if any). 4913 TaskResultTy Result; 4914 if (!Privates.empty()) { 4915 emitPrivatesInit(CGF, D, KmpTaskSharedsPtr, Base, KmpTaskTWithPrivatesQTyRD, 4916 SharedsTy, SharedsPtrTy, Data, Privates, 4917 /*ForDup=*/false); 4918 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && 4919 (!Data.LastprivateVars.empty() || checkInitIsRequired(CGF, Privates))) { 4920 Result.TaskDupFn = emitTaskDupFunction( 4921 CGM, Loc, D, KmpTaskTWithPrivatesPtrQTy, KmpTaskTWithPrivatesQTyRD, 4922 KmpTaskTQTyRD, SharedsTy, SharedsPtrTy, Data, Privates, 4923 /*WithLastIter=*/!Data.LastprivateVars.empty()); 4924 } 4925 } 4926 // Fields of union "kmp_cmplrdata_t" for destructors and priority. 4927 enum { Priority = 0, Destructors = 1 }; 4928 // Provide pointer to function with destructors for privates. 4929 auto FI = std::next(KmpTaskTQTyRD->field_begin(), Data1); 4930 const RecordDecl *KmpCmplrdataUD = 4931 (*FI)->getType()->getAsUnionType()->getDecl(); 4932 if (NeedsCleanup) { 4933 llvm::Value *DestructorFn = emitDestructorsFunction( 4934 CGM, Loc, KmpInt32Ty, KmpTaskTWithPrivatesPtrQTy, 4935 KmpTaskTWithPrivatesQTy); 4936 LValue Data1LV = CGF.EmitLValueForField(TDBase, *FI); 4937 LValue DestructorsLV = CGF.EmitLValueForField( 4938 Data1LV, *std::next(KmpCmplrdataUD->field_begin(), Destructors)); 4939 CGF.EmitStoreOfScalar(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4940 DestructorFn, KmpRoutineEntryPtrTy), 4941 DestructorsLV); 4942 } 4943 // Set priority. 4944 if (Data.Priority.getInt()) { 4945 LValue Data2LV = CGF.EmitLValueForField( 4946 TDBase, *std::next(KmpTaskTQTyRD->field_begin(), Data2)); 4947 LValue PriorityLV = CGF.EmitLValueForField( 4948 Data2LV, *std::next(KmpCmplrdataUD->field_begin(), Priority)); 4949 CGF.EmitStoreOfScalar(Data.Priority.getPointer(), PriorityLV); 4950 } 4951 Result.NewTask = NewTask; 4952 Result.TaskEntry = TaskEntry; 4953 Result.NewTaskNewTaskTTy = NewTaskNewTaskTTy; 4954 Result.TDBase = TDBase; 4955 Result.KmpTaskTQTyRD = KmpTaskTQTyRD; 4956 return Result; 4957 } 4958 4959 void CGOpenMPRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 4960 const OMPExecutableDirective &D, 4961 llvm::Value *TaskFunction, 4962 QualType SharedsTy, Address Shareds, 4963 const Expr *IfCond, 4964 const OMPTaskDataTy &Data) { 4965 if (!CGF.HaveInsertPoint()) 4966 return; 4967 4968 TaskResultTy Result = 4969 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); 4970 llvm::Value *NewTask = Result.NewTask; 4971 llvm::Value *TaskEntry = Result.TaskEntry; 4972 llvm::Value *NewTaskNewTaskTTy = Result.NewTaskNewTaskTTy; 4973 LValue TDBase = Result.TDBase; 4974 const RecordDecl *KmpTaskTQTyRD = Result.KmpTaskTQTyRD; 4975 ASTContext &C = CGM.getContext(); 4976 // Process list of dependences. 4977 Address DependenciesArray = Address::invalid(); 4978 unsigned NumDependencies = Data.Dependences.size(); 4979 if (NumDependencies) { 4980 // Dependence kind for RTL. 4981 enum RTLDependenceKindTy { DepIn = 0x01, DepInOut = 0x3 }; 4982 enum RTLDependInfoFieldsTy { BaseAddr, Len, Flags }; 4983 RecordDecl *KmpDependInfoRD; 4984 QualType FlagsTy = 4985 C.getIntTypeForBitwidth(C.getTypeSize(C.BoolTy), /*Signed=*/false); 4986 llvm::Type *LLVMFlagsTy = CGF.ConvertTypeForMem(FlagsTy); 4987 if (KmpDependInfoTy.isNull()) { 4988 KmpDependInfoRD = C.buildImplicitRecord("kmp_depend_info"); 4989 KmpDependInfoRD->startDefinition(); 4990 addFieldToRecordDecl(C, KmpDependInfoRD, C.getIntPtrType()); 4991 addFieldToRecordDecl(C, KmpDependInfoRD, C.getSizeType()); 4992 addFieldToRecordDecl(C, KmpDependInfoRD, FlagsTy); 4993 KmpDependInfoRD->completeDefinition(); 4994 KmpDependInfoTy = C.getRecordType(KmpDependInfoRD); 4995 } else { 4996 KmpDependInfoRD = cast<RecordDecl>(KmpDependInfoTy->getAsTagDecl()); 4997 } 4998 CharUnits DependencySize = C.getTypeSizeInChars(KmpDependInfoTy); 4999 // Define type kmp_depend_info[<Dependences.size()>]; 5000 QualType KmpDependInfoArrayTy = C.getConstantArrayType( 5001 KmpDependInfoTy, llvm::APInt(/*numBits=*/64, NumDependencies), 5002 ArrayType::Normal, /*IndexTypeQuals=*/0); 5003 // kmp_depend_info[<Dependences.size()>] deps; 5004 DependenciesArray = 5005 CGF.CreateMemTemp(KmpDependInfoArrayTy, ".dep.arr.addr"); 5006 for (unsigned I = 0; I < NumDependencies; ++I) { 5007 const Expr *E = Data.Dependences[I].second; 5008 LValue Addr = CGF.EmitLValue(E); 5009 llvm::Value *Size; 5010 QualType Ty = E->getType(); 5011 if (const auto *ASE = 5012 dyn_cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts())) { 5013 LValue UpAddrLVal = 5014 CGF.EmitOMPArraySectionExpr(ASE, /*LowerBound=*/false); 5015 llvm::Value *UpAddr = 5016 CGF.Builder.CreateConstGEP1_32(UpAddrLVal.getPointer(), /*Idx0=*/1); 5017 llvm::Value *LowIntPtr = 5018 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGM.SizeTy); 5019 llvm::Value *UpIntPtr = CGF.Builder.CreatePtrToInt(UpAddr, CGM.SizeTy); 5020 Size = CGF.Builder.CreateNUWSub(UpIntPtr, LowIntPtr); 5021 } else { 5022 Size = CGF.getTypeSize(Ty); 5023 } 5024 LValue Base = CGF.MakeAddrLValue( 5025 CGF.Builder.CreateConstArrayGEP(DependenciesArray, I, DependencySize), 5026 KmpDependInfoTy); 5027 // deps[i].base_addr = &<Dependences[i].second>; 5028 LValue BaseAddrLVal = CGF.EmitLValueForField( 5029 Base, *std::next(KmpDependInfoRD->field_begin(), BaseAddr)); 5030 CGF.EmitStoreOfScalar( 5031 CGF.Builder.CreatePtrToInt(Addr.getPointer(), CGF.IntPtrTy), 5032 BaseAddrLVal); 5033 // deps[i].len = sizeof(<Dependences[i].second>); 5034 LValue LenLVal = CGF.EmitLValueForField( 5035 Base, *std::next(KmpDependInfoRD->field_begin(), Len)); 5036 CGF.EmitStoreOfScalar(Size, LenLVal); 5037 // deps[i].flags = <Dependences[i].first>; 5038 RTLDependenceKindTy DepKind; 5039 switch (Data.Dependences[I].first) { 5040 case OMPC_DEPEND_in: 5041 DepKind = DepIn; 5042 break; 5043 // Out and InOut dependencies must use the same code. 5044 case OMPC_DEPEND_out: 5045 case OMPC_DEPEND_inout: 5046 DepKind = DepInOut; 5047 break; 5048 case OMPC_DEPEND_source: 5049 case OMPC_DEPEND_sink: 5050 case OMPC_DEPEND_unknown: 5051 llvm_unreachable("Unknown task dependence type"); 5052 } 5053 LValue FlagsLVal = CGF.EmitLValueForField( 5054 Base, *std::next(KmpDependInfoRD->field_begin(), Flags)); 5055 CGF.EmitStoreOfScalar(llvm::ConstantInt::get(LLVMFlagsTy, DepKind), 5056 FlagsLVal); 5057 } 5058 DependenciesArray = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5059 CGF.Builder.CreateStructGEP(DependenciesArray, 0, CharUnits::Zero()), 5060 CGF.VoidPtrTy); 5061 } 5062 5063 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() 5064 // libcall. 5065 // Build kmp_int32 __kmpc_omp_task_with_deps(ident_t *, kmp_int32 gtid, 5066 // kmp_task_t *new_task, kmp_int32 ndeps, kmp_depend_info_t *dep_list, 5067 // kmp_int32 ndeps_noalias, kmp_depend_info_t *noalias_dep_list) if dependence 5068 // list is not empty 5069 llvm::Value *ThreadID = getThreadID(CGF, Loc); 5070 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); 5071 llvm::Value *TaskArgs[] = { UpLoc, ThreadID, NewTask }; 5072 llvm::Value *DepTaskArgs[7]; 5073 if (NumDependencies) { 5074 DepTaskArgs[0] = UpLoc; 5075 DepTaskArgs[1] = ThreadID; 5076 DepTaskArgs[2] = NewTask; 5077 DepTaskArgs[3] = CGF.Builder.getInt32(NumDependencies); 5078 DepTaskArgs[4] = DependenciesArray.getPointer(); 5079 DepTaskArgs[5] = CGF.Builder.getInt32(0); 5080 DepTaskArgs[6] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 5081 } 5082 auto &&ThenCodeGen = [this, &Data, TDBase, KmpTaskTQTyRD, NumDependencies, 5083 &TaskArgs, 5084 &DepTaskArgs](CodeGenFunction &CGF, PrePostActionTy &) { 5085 if (!Data.Tied) { 5086 auto PartIdFI = std::next(KmpTaskTQTyRD->field_begin(), KmpTaskTPartId); 5087 LValue PartIdLVal = CGF.EmitLValueForField(TDBase, *PartIdFI); 5088 CGF.EmitStoreOfScalar(CGF.Builder.getInt32(0), PartIdLVal); 5089 } 5090 if (NumDependencies) { 5091 CGF.EmitRuntimeCall( 5092 createRuntimeFunction(OMPRTL__kmpc_omp_task_with_deps), DepTaskArgs); 5093 } else { 5094 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_task), 5095 TaskArgs); 5096 } 5097 // Check if parent region is untied and build return for untied task; 5098 if (auto *Region = 5099 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 5100 Region->emitUntiedSwitch(CGF); 5101 }; 5102 5103 llvm::Value *DepWaitTaskArgs[6]; 5104 if (NumDependencies) { 5105 DepWaitTaskArgs[0] = UpLoc; 5106 DepWaitTaskArgs[1] = ThreadID; 5107 DepWaitTaskArgs[2] = CGF.Builder.getInt32(NumDependencies); 5108 DepWaitTaskArgs[3] = DependenciesArray.getPointer(); 5109 DepWaitTaskArgs[4] = CGF.Builder.getInt32(0); 5110 DepWaitTaskArgs[5] = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 5111 } 5112 auto &&ElseCodeGen = [&TaskArgs, ThreadID, NewTaskNewTaskTTy, TaskEntry, 5113 NumDependencies, &DepWaitTaskArgs, 5114 Loc](CodeGenFunction &CGF, PrePostActionTy &) { 5115 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 5116 CodeGenFunction::RunCleanupsScope LocalScope(CGF); 5117 // Build void __kmpc_omp_wait_deps(ident_t *, kmp_int32 gtid, 5118 // kmp_int32 ndeps, kmp_depend_info_t *dep_list, kmp_int32 5119 // ndeps_noalias, kmp_depend_info_t *noalias_dep_list); if dependence info 5120 // is specified. 5121 if (NumDependencies) 5122 CGF.EmitRuntimeCall(RT.createRuntimeFunction(OMPRTL__kmpc_omp_wait_deps), 5123 DepWaitTaskArgs); 5124 // Call proxy_task_entry(gtid, new_task); 5125 auto &&CodeGen = [TaskEntry, ThreadID, NewTaskNewTaskTTy, 5126 Loc](CodeGenFunction &CGF, PrePostActionTy &Action) { 5127 Action.Enter(CGF); 5128 llvm::Value *OutlinedFnArgs[] = {ThreadID, NewTaskNewTaskTTy}; 5129 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, Loc, TaskEntry, 5130 OutlinedFnArgs); 5131 }; 5132 5133 // Build void __kmpc_omp_task_begin_if0(ident_t *, kmp_int32 gtid, 5134 // kmp_task_t *new_task); 5135 // Build void __kmpc_omp_task_complete_if0(ident_t *, kmp_int32 gtid, 5136 // kmp_task_t *new_task); 5137 RegionCodeGenTy RCG(CodeGen); 5138 CommonActionTy Action( 5139 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_begin_if0), TaskArgs, 5140 RT.createRuntimeFunction(OMPRTL__kmpc_omp_task_complete_if0), TaskArgs); 5141 RCG.setAction(Action); 5142 RCG(CGF); 5143 }; 5144 5145 if (IfCond) { 5146 emitOMPIfClause(CGF, IfCond, ThenCodeGen, ElseCodeGen); 5147 } else { 5148 RegionCodeGenTy ThenRCG(ThenCodeGen); 5149 ThenRCG(CGF); 5150 } 5151 } 5152 5153 void CGOpenMPRuntime::emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, 5154 const OMPLoopDirective &D, 5155 llvm::Value *TaskFunction, 5156 QualType SharedsTy, Address Shareds, 5157 const Expr *IfCond, 5158 const OMPTaskDataTy &Data) { 5159 if (!CGF.HaveInsertPoint()) 5160 return; 5161 TaskResultTy Result = 5162 emitTaskInit(CGF, Loc, D, TaskFunction, SharedsTy, Shareds, Data); 5163 // NOTE: routine and part_id fields are initialized by __kmpc_omp_task_alloc() 5164 // libcall. 5165 // Call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t *task, int 5166 // if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int nogroup, int 5167 // sched, kmp_uint64 grainsize, void *task_dup); 5168 llvm::Value *ThreadID = getThreadID(CGF, Loc); 5169 llvm::Value *UpLoc = emitUpdateLocation(CGF, Loc); 5170 llvm::Value *IfVal; 5171 if (IfCond) { 5172 IfVal = CGF.Builder.CreateIntCast(CGF.EvaluateExprAsBool(IfCond), CGF.IntTy, 5173 /*isSigned=*/true); 5174 } else { 5175 IfVal = llvm::ConstantInt::getSigned(CGF.IntTy, /*V=*/1); 5176 } 5177 5178 LValue LBLVal = CGF.EmitLValueForField( 5179 Result.TDBase, 5180 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTLowerBound)); 5181 const auto *LBVar = 5182 cast<VarDecl>(cast<DeclRefExpr>(D.getLowerBoundVariable())->getDecl()); 5183 CGF.EmitAnyExprToMem(LBVar->getInit(), LBLVal.getAddress(), LBLVal.getQuals(), 5184 /*IsInitializer=*/true); 5185 LValue UBLVal = CGF.EmitLValueForField( 5186 Result.TDBase, 5187 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTUpperBound)); 5188 const auto *UBVar = 5189 cast<VarDecl>(cast<DeclRefExpr>(D.getUpperBoundVariable())->getDecl()); 5190 CGF.EmitAnyExprToMem(UBVar->getInit(), UBLVal.getAddress(), UBLVal.getQuals(), 5191 /*IsInitializer=*/true); 5192 LValue StLVal = CGF.EmitLValueForField( 5193 Result.TDBase, 5194 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTStride)); 5195 const auto *StVar = 5196 cast<VarDecl>(cast<DeclRefExpr>(D.getStrideVariable())->getDecl()); 5197 CGF.EmitAnyExprToMem(StVar->getInit(), StLVal.getAddress(), StLVal.getQuals(), 5198 /*IsInitializer=*/true); 5199 // Store reductions address. 5200 LValue RedLVal = CGF.EmitLValueForField( 5201 Result.TDBase, 5202 *std::next(Result.KmpTaskTQTyRD->field_begin(), KmpTaskTReductions)); 5203 if (Data.Reductions) { 5204 CGF.EmitStoreOfScalar(Data.Reductions, RedLVal); 5205 } else { 5206 CGF.EmitNullInitialization(RedLVal.getAddress(), 5207 CGF.getContext().VoidPtrTy); 5208 } 5209 enum { NoSchedule = 0, Grainsize = 1, NumTasks = 2 }; 5210 llvm::Value *TaskArgs[] = { 5211 UpLoc, 5212 ThreadID, 5213 Result.NewTask, 5214 IfVal, 5215 LBLVal.getPointer(), 5216 UBLVal.getPointer(), 5217 CGF.EmitLoadOfScalar(StLVal, Loc), 5218 llvm::ConstantInt::getNullValue( 5219 CGF.IntTy), // Always 0 because taskgroup emitted by the compiler 5220 llvm::ConstantInt::getSigned( 5221 CGF.IntTy, Data.Schedule.getPointer() 5222 ? Data.Schedule.getInt() ? NumTasks : Grainsize 5223 : NoSchedule), 5224 Data.Schedule.getPointer() 5225 ? CGF.Builder.CreateIntCast(Data.Schedule.getPointer(), CGF.Int64Ty, 5226 /*isSigned=*/false) 5227 : llvm::ConstantInt::get(CGF.Int64Ty, /*V=*/0), 5228 Result.TaskDupFn ? CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5229 Result.TaskDupFn, CGF.VoidPtrTy) 5230 : llvm::ConstantPointerNull::get(CGF.VoidPtrTy)}; 5231 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_taskloop), TaskArgs); 5232 } 5233 5234 /// Emit reduction operation for each element of array (required for 5235 /// array sections) LHS op = RHS. 5236 /// \param Type Type of array. 5237 /// \param LHSVar Variable on the left side of the reduction operation 5238 /// (references element of array in original variable). 5239 /// \param RHSVar Variable on the right side of the reduction operation 5240 /// (references element of array in original variable). 5241 /// \param RedOpGen Generator of reduction operation with use of LHSVar and 5242 /// RHSVar. 5243 static void EmitOMPAggregateReduction( 5244 CodeGenFunction &CGF, QualType Type, const VarDecl *LHSVar, 5245 const VarDecl *RHSVar, 5246 const llvm::function_ref<void(CodeGenFunction &CGF, const Expr *, 5247 const Expr *, const Expr *)> &RedOpGen, 5248 const Expr *XExpr = nullptr, const Expr *EExpr = nullptr, 5249 const Expr *UpExpr = nullptr) { 5250 // Perform element-by-element initialization. 5251 QualType ElementTy; 5252 Address LHSAddr = CGF.GetAddrOfLocalVar(LHSVar); 5253 Address RHSAddr = CGF.GetAddrOfLocalVar(RHSVar); 5254 5255 // Drill down to the base element type on both arrays. 5256 const ArrayType *ArrayTy = Type->getAsArrayTypeUnsafe(); 5257 llvm::Value *NumElements = CGF.emitArrayLength(ArrayTy, ElementTy, LHSAddr); 5258 5259 llvm::Value *RHSBegin = RHSAddr.getPointer(); 5260 llvm::Value *LHSBegin = LHSAddr.getPointer(); 5261 // Cast from pointer to array type to pointer to single element. 5262 llvm::Value *LHSEnd = CGF.Builder.CreateGEP(LHSBegin, NumElements); 5263 // The basic structure here is a while-do loop. 5264 llvm::BasicBlock *BodyBB = CGF.createBasicBlock("omp.arraycpy.body"); 5265 llvm::BasicBlock *DoneBB = CGF.createBasicBlock("omp.arraycpy.done"); 5266 llvm::Value *IsEmpty = 5267 CGF.Builder.CreateICmpEQ(LHSBegin, LHSEnd, "omp.arraycpy.isempty"); 5268 CGF.Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 5269 5270 // Enter the loop body, making that address the current address. 5271 llvm::BasicBlock *EntryBB = CGF.Builder.GetInsertBlock(); 5272 CGF.EmitBlock(BodyBB); 5273 5274 CharUnits ElementSize = CGF.getContext().getTypeSizeInChars(ElementTy); 5275 5276 llvm::PHINode *RHSElementPHI = CGF.Builder.CreatePHI( 5277 RHSBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 5278 RHSElementPHI->addIncoming(RHSBegin, EntryBB); 5279 Address RHSElementCurrent = 5280 Address(RHSElementPHI, 5281 RHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 5282 5283 llvm::PHINode *LHSElementPHI = CGF.Builder.CreatePHI( 5284 LHSBegin->getType(), 2, "omp.arraycpy.destElementPast"); 5285 LHSElementPHI->addIncoming(LHSBegin, EntryBB); 5286 Address LHSElementCurrent = 5287 Address(LHSElementPHI, 5288 LHSAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 5289 5290 // Emit copy. 5291 CodeGenFunction::OMPPrivateScope Scope(CGF); 5292 Scope.addPrivate(LHSVar, [=]() { return LHSElementCurrent; }); 5293 Scope.addPrivate(RHSVar, [=]() { return RHSElementCurrent; }); 5294 Scope.Privatize(); 5295 RedOpGen(CGF, XExpr, EExpr, UpExpr); 5296 Scope.ForceCleanup(); 5297 5298 // Shift the address forward by one element. 5299 llvm::Value *LHSElementNext = CGF.Builder.CreateConstGEP1_32( 5300 LHSElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 5301 llvm::Value *RHSElementNext = CGF.Builder.CreateConstGEP1_32( 5302 RHSElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element"); 5303 // Check whether we've reached the end. 5304 llvm::Value *Done = 5305 CGF.Builder.CreateICmpEQ(LHSElementNext, LHSEnd, "omp.arraycpy.done"); 5306 CGF.Builder.CreateCondBr(Done, DoneBB, BodyBB); 5307 LHSElementPHI->addIncoming(LHSElementNext, CGF.Builder.GetInsertBlock()); 5308 RHSElementPHI->addIncoming(RHSElementNext, CGF.Builder.GetInsertBlock()); 5309 5310 // Done. 5311 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 5312 } 5313 5314 /// Emit reduction combiner. If the combiner is a simple expression emit it as 5315 /// is, otherwise consider it as combiner of UDR decl and emit it as a call of 5316 /// UDR combiner function. 5317 static void emitReductionCombiner(CodeGenFunction &CGF, 5318 const Expr *ReductionOp) { 5319 if (const auto *CE = dyn_cast<CallExpr>(ReductionOp)) 5320 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(CE->getCallee())) 5321 if (const auto *DRE = 5322 dyn_cast<DeclRefExpr>(OVE->getSourceExpr()->IgnoreImpCasts())) 5323 if (const auto *DRD = 5324 dyn_cast<OMPDeclareReductionDecl>(DRE->getDecl())) { 5325 std::pair<llvm::Function *, llvm::Function *> Reduction = 5326 CGF.CGM.getOpenMPRuntime().getUserDefinedReduction(DRD); 5327 RValue Func = RValue::get(Reduction.first); 5328 CodeGenFunction::OpaqueValueMapping Map(CGF, OVE, Func); 5329 CGF.EmitIgnoredExpr(ReductionOp); 5330 return; 5331 } 5332 CGF.EmitIgnoredExpr(ReductionOp); 5333 } 5334 5335 llvm::Value *CGOpenMPRuntime::emitReductionFunction( 5336 CodeGenModule &CGM, SourceLocation Loc, llvm::Type *ArgsType, 5337 ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, 5338 ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps) { 5339 ASTContext &C = CGM.getContext(); 5340 5341 // void reduction_func(void *LHSArg, void *RHSArg); 5342 FunctionArgList Args; 5343 ImplicitParamDecl LHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5344 ImplicitParamDecl::Other); 5345 ImplicitParamDecl RHSArg(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5346 ImplicitParamDecl::Other); 5347 Args.push_back(&LHSArg); 5348 Args.push_back(&RHSArg); 5349 const auto &CGFI = 5350 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 5351 std::string Name = getName({"omp", "reduction", "reduction_func"}); 5352 auto *Fn = llvm::Function::Create(CGM.getTypes().GetFunctionType(CGFI), 5353 llvm::GlobalValue::InternalLinkage, Name, 5354 &CGM.getModule()); 5355 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, CGFI); 5356 Fn->setDoesNotRecurse(); 5357 CodeGenFunction CGF(CGM); 5358 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, CGFI, Args, Loc, Loc); 5359 5360 // Dst = (void*[n])(LHSArg); 5361 // Src = (void*[n])(RHSArg); 5362 Address LHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5363 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&LHSArg)), 5364 ArgsType), CGF.getPointerAlign()); 5365 Address RHS(CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5366 CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&RHSArg)), 5367 ArgsType), CGF.getPointerAlign()); 5368 5369 // ... 5370 // *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); 5371 // ... 5372 CodeGenFunction::OMPPrivateScope Scope(CGF); 5373 auto IPriv = Privates.begin(); 5374 unsigned Idx = 0; 5375 for (unsigned I = 0, E = ReductionOps.size(); I < E; ++I, ++IPriv, ++Idx) { 5376 const auto *RHSVar = 5377 cast<VarDecl>(cast<DeclRefExpr>(RHSExprs[I])->getDecl()); 5378 Scope.addPrivate(RHSVar, [&CGF, RHS, Idx, RHSVar]() { 5379 return emitAddrOfVarFromArray(CGF, RHS, Idx, RHSVar); 5380 }); 5381 const auto *LHSVar = 5382 cast<VarDecl>(cast<DeclRefExpr>(LHSExprs[I])->getDecl()); 5383 Scope.addPrivate(LHSVar, [&CGF, LHS, Idx, LHSVar]() { 5384 return emitAddrOfVarFromArray(CGF, LHS, Idx, LHSVar); 5385 }); 5386 QualType PrivTy = (*IPriv)->getType(); 5387 if (PrivTy->isVariablyModifiedType()) { 5388 // Get array size and emit VLA type. 5389 ++Idx; 5390 Address Elem = 5391 CGF.Builder.CreateConstArrayGEP(LHS, Idx, CGF.getPointerSize()); 5392 llvm::Value *Ptr = CGF.Builder.CreateLoad(Elem); 5393 const VariableArrayType *VLA = 5394 CGF.getContext().getAsVariableArrayType(PrivTy); 5395 const auto *OVE = cast<OpaqueValueExpr>(VLA->getSizeExpr()); 5396 CodeGenFunction::OpaqueValueMapping OpaqueMap( 5397 CGF, OVE, RValue::get(CGF.Builder.CreatePtrToInt(Ptr, CGF.SizeTy))); 5398 CGF.EmitVariablyModifiedType(PrivTy); 5399 } 5400 } 5401 Scope.Privatize(); 5402 IPriv = Privates.begin(); 5403 auto ILHS = LHSExprs.begin(); 5404 auto IRHS = RHSExprs.begin(); 5405 for (const Expr *E : ReductionOps) { 5406 if ((*IPriv)->getType()->isArrayType()) { 5407 // Emit reduction for array section. 5408 const auto *LHSVar = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 5409 const auto *RHSVar = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 5410 EmitOMPAggregateReduction( 5411 CGF, (*IPriv)->getType(), LHSVar, RHSVar, 5412 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { 5413 emitReductionCombiner(CGF, E); 5414 }); 5415 } else { 5416 // Emit reduction for array subscript or single variable. 5417 emitReductionCombiner(CGF, E); 5418 } 5419 ++IPriv; 5420 ++ILHS; 5421 ++IRHS; 5422 } 5423 Scope.ForceCleanup(); 5424 CGF.FinishFunction(); 5425 return Fn; 5426 } 5427 5428 void CGOpenMPRuntime::emitSingleReductionCombiner(CodeGenFunction &CGF, 5429 const Expr *ReductionOp, 5430 const Expr *PrivateRef, 5431 const DeclRefExpr *LHS, 5432 const DeclRefExpr *RHS) { 5433 if (PrivateRef->getType()->isArrayType()) { 5434 // Emit reduction for array section. 5435 const auto *LHSVar = cast<VarDecl>(LHS->getDecl()); 5436 const auto *RHSVar = cast<VarDecl>(RHS->getDecl()); 5437 EmitOMPAggregateReduction( 5438 CGF, PrivateRef->getType(), LHSVar, RHSVar, 5439 [=](CodeGenFunction &CGF, const Expr *, const Expr *, const Expr *) { 5440 emitReductionCombiner(CGF, ReductionOp); 5441 }); 5442 } else { 5443 // Emit reduction for array subscript or single variable. 5444 emitReductionCombiner(CGF, ReductionOp); 5445 } 5446 } 5447 5448 void CGOpenMPRuntime::emitReduction(CodeGenFunction &CGF, SourceLocation Loc, 5449 ArrayRef<const Expr *> Privates, 5450 ArrayRef<const Expr *> LHSExprs, 5451 ArrayRef<const Expr *> RHSExprs, 5452 ArrayRef<const Expr *> ReductionOps, 5453 ReductionOptionsTy Options) { 5454 if (!CGF.HaveInsertPoint()) 5455 return; 5456 5457 bool WithNowait = Options.WithNowait; 5458 bool SimpleReduction = Options.SimpleReduction; 5459 5460 // Next code should be emitted for reduction: 5461 // 5462 // static kmp_critical_name lock = { 0 }; 5463 // 5464 // void reduce_func(void *lhs[<n>], void *rhs[<n>]) { 5465 // *(Type0*)lhs[0] = ReductionOperation0(*(Type0*)lhs[0], *(Type0*)rhs[0]); 5466 // ... 5467 // *(Type<n>-1*)lhs[<n>-1] = ReductionOperation<n>-1(*(Type<n>-1*)lhs[<n>-1], 5468 // *(Type<n>-1*)rhs[<n>-1]); 5469 // } 5470 // 5471 // ... 5472 // void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; 5473 // switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 5474 // RedList, reduce_func, &<lock>)) { 5475 // case 1: 5476 // ... 5477 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 5478 // ... 5479 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 5480 // break; 5481 // case 2: 5482 // ... 5483 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 5484 // ... 5485 // [__kmpc_end_reduce(<loc>, <gtid>, &<lock>);] 5486 // break; 5487 // default:; 5488 // } 5489 // 5490 // if SimpleReduction is true, only the next code is generated: 5491 // ... 5492 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 5493 // ... 5494 5495 ASTContext &C = CGM.getContext(); 5496 5497 if (SimpleReduction) { 5498 CodeGenFunction::RunCleanupsScope Scope(CGF); 5499 auto IPriv = Privates.begin(); 5500 auto ILHS = LHSExprs.begin(); 5501 auto IRHS = RHSExprs.begin(); 5502 for (const Expr *E : ReductionOps) { 5503 emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), 5504 cast<DeclRefExpr>(*IRHS)); 5505 ++IPriv; 5506 ++ILHS; 5507 ++IRHS; 5508 } 5509 return; 5510 } 5511 5512 // 1. Build a list of reduction variables. 5513 // void *RedList[<n>] = {<ReductionVars>[0], ..., <ReductionVars>[<n>-1]}; 5514 auto Size = RHSExprs.size(); 5515 for (const Expr *E : Privates) { 5516 if (E->getType()->isVariablyModifiedType()) 5517 // Reserve place for array size. 5518 ++Size; 5519 } 5520 llvm::APInt ArraySize(/*unsigned int numBits=*/32, Size); 5521 QualType ReductionArrayTy = 5522 C.getConstantArrayType(C.VoidPtrTy, ArraySize, ArrayType::Normal, 5523 /*IndexTypeQuals=*/0); 5524 Address ReductionList = 5525 CGF.CreateMemTemp(ReductionArrayTy, ".omp.reduction.red_list"); 5526 auto IPriv = Privates.begin(); 5527 unsigned Idx = 0; 5528 for (unsigned I = 0, E = RHSExprs.size(); I < E; ++I, ++IPriv, ++Idx) { 5529 Address Elem = 5530 CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, CGF.getPointerSize()); 5531 CGF.Builder.CreateStore( 5532 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5533 CGF.EmitLValue(RHSExprs[I]).getPointer(), CGF.VoidPtrTy), 5534 Elem); 5535 if ((*IPriv)->getType()->isVariablyModifiedType()) { 5536 // Store array size. 5537 ++Idx; 5538 Elem = CGF.Builder.CreateConstArrayGEP(ReductionList, Idx, 5539 CGF.getPointerSize()); 5540 llvm::Value *Size = CGF.Builder.CreateIntCast( 5541 CGF.getVLASize( 5542 CGF.getContext().getAsVariableArrayType((*IPriv)->getType())) 5543 .NumElts, 5544 CGF.SizeTy, /*isSigned=*/false); 5545 CGF.Builder.CreateStore(CGF.Builder.CreateIntToPtr(Size, CGF.VoidPtrTy), 5546 Elem); 5547 } 5548 } 5549 5550 // 2. Emit reduce_func(). 5551 llvm::Value *ReductionFn = emitReductionFunction( 5552 CGM, Loc, CGF.ConvertTypeForMem(ReductionArrayTy)->getPointerTo(), 5553 Privates, LHSExprs, RHSExprs, ReductionOps); 5554 5555 // 3. Create static kmp_critical_name lock = { 0 }; 5556 std::string Name = getName({"reduction"}); 5557 llvm::Value *Lock = getCriticalRegionLock(Name); 5558 5559 // 4. Build res = __kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), 5560 // RedList, reduce_func, &<lock>); 5561 llvm::Value *IdentTLoc = emitUpdateLocation(CGF, Loc, OMP_ATOMIC_REDUCE); 5562 llvm::Value *ThreadId = getThreadID(CGF, Loc); 5563 llvm::Value *ReductionArrayTySize = CGF.getTypeSize(ReductionArrayTy); 5564 llvm::Value *RL = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 5565 ReductionList.getPointer(), CGF.VoidPtrTy); 5566 llvm::Value *Args[] = { 5567 IdentTLoc, // ident_t *<loc> 5568 ThreadId, // i32 <gtid> 5569 CGF.Builder.getInt32(RHSExprs.size()), // i32 <n> 5570 ReductionArrayTySize, // size_type sizeof(RedList) 5571 RL, // void *RedList 5572 ReductionFn, // void (*) (void *, void *) <reduce_func> 5573 Lock // kmp_critical_name *&<lock> 5574 }; 5575 llvm::Value *Res = CGF.EmitRuntimeCall( 5576 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_reduce_nowait 5577 : OMPRTL__kmpc_reduce), 5578 Args); 5579 5580 // 5. Build switch(res) 5581 llvm::BasicBlock *DefaultBB = CGF.createBasicBlock(".omp.reduction.default"); 5582 llvm::SwitchInst *SwInst = 5583 CGF.Builder.CreateSwitch(Res, DefaultBB, /*NumCases=*/2); 5584 5585 // 6. Build case 1: 5586 // ... 5587 // <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); 5588 // ... 5589 // __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 5590 // break; 5591 llvm::BasicBlock *Case1BB = CGF.createBasicBlock(".omp.reduction.case1"); 5592 SwInst->addCase(CGF.Builder.getInt32(1), Case1BB); 5593 CGF.EmitBlock(Case1BB); 5594 5595 // Add emission of __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); 5596 llvm::Value *EndArgs[] = { 5597 IdentTLoc, // ident_t *<loc> 5598 ThreadId, // i32 <gtid> 5599 Lock // kmp_critical_name *&<lock> 5600 }; 5601 auto &&CodeGen = [Privates, LHSExprs, RHSExprs, ReductionOps]( 5602 CodeGenFunction &CGF, PrePostActionTy &Action) { 5603 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 5604 auto IPriv = Privates.begin(); 5605 auto ILHS = LHSExprs.begin(); 5606 auto IRHS = RHSExprs.begin(); 5607 for (const Expr *E : ReductionOps) { 5608 RT.emitSingleReductionCombiner(CGF, E, *IPriv, cast<DeclRefExpr>(*ILHS), 5609 cast<DeclRefExpr>(*IRHS)); 5610 ++IPriv; 5611 ++ILHS; 5612 ++IRHS; 5613 } 5614 }; 5615 RegionCodeGenTy RCG(CodeGen); 5616 CommonActionTy Action( 5617 nullptr, llvm::None, 5618 createRuntimeFunction(WithNowait ? OMPRTL__kmpc_end_reduce_nowait 5619 : OMPRTL__kmpc_end_reduce), 5620 EndArgs); 5621 RCG.setAction(Action); 5622 RCG(CGF); 5623 5624 CGF.EmitBranch(DefaultBB); 5625 5626 // 7. Build case 2: 5627 // ... 5628 // Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); 5629 // ... 5630 // break; 5631 llvm::BasicBlock *Case2BB = CGF.createBasicBlock(".omp.reduction.case2"); 5632 SwInst->addCase(CGF.Builder.getInt32(2), Case2BB); 5633 CGF.EmitBlock(Case2BB); 5634 5635 auto &&AtomicCodeGen = [Loc, Privates, LHSExprs, RHSExprs, ReductionOps]( 5636 CodeGenFunction &CGF, PrePostActionTy &Action) { 5637 auto ILHS = LHSExprs.begin(); 5638 auto IRHS = RHSExprs.begin(); 5639 auto IPriv = Privates.begin(); 5640 for (const Expr *E : ReductionOps) { 5641 const Expr *XExpr = nullptr; 5642 const Expr *EExpr = nullptr; 5643 const Expr *UpExpr = nullptr; 5644 BinaryOperatorKind BO = BO_Comma; 5645 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 5646 if (BO->getOpcode() == BO_Assign) { 5647 XExpr = BO->getLHS(); 5648 UpExpr = BO->getRHS(); 5649 } 5650 } 5651 // Try to emit update expression as a simple atomic. 5652 const Expr *RHSExpr = UpExpr; 5653 if (RHSExpr) { 5654 // Analyze RHS part of the whole expression. 5655 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>( 5656 RHSExpr->IgnoreParenImpCasts())) { 5657 // If this is a conditional operator, analyze its condition for 5658 // min/max reduction operator. 5659 RHSExpr = ACO->getCond(); 5660 } 5661 if (const auto *BORHS = 5662 dyn_cast<BinaryOperator>(RHSExpr->IgnoreParenImpCasts())) { 5663 EExpr = BORHS->getRHS(); 5664 BO = BORHS->getOpcode(); 5665 } 5666 } 5667 if (XExpr) { 5668 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 5669 auto &&AtomicRedGen = [BO, VD, 5670 Loc](CodeGenFunction &CGF, const Expr *XExpr, 5671 const Expr *EExpr, const Expr *UpExpr) { 5672 LValue X = CGF.EmitLValue(XExpr); 5673 RValue E; 5674 if (EExpr) 5675 E = CGF.EmitAnyExpr(EExpr); 5676 CGF.EmitOMPAtomicSimpleUpdateExpr( 5677 X, E, BO, /*IsXLHSInRHSPart=*/true, 5678 llvm::AtomicOrdering::Monotonic, Loc, 5679 [&CGF, UpExpr, VD, Loc](RValue XRValue) { 5680 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5681 PrivateScope.addPrivate( 5682 VD, [&CGF, VD, XRValue, Loc]() { 5683 Address LHSTemp = CGF.CreateMemTemp(VD->getType()); 5684 CGF.emitOMPSimpleStore( 5685 CGF.MakeAddrLValue(LHSTemp, VD->getType()), XRValue, 5686 VD->getType().getNonReferenceType(), Loc); 5687 return LHSTemp; 5688 }); 5689 (void)PrivateScope.Privatize(); 5690 return CGF.EmitAnyExpr(UpExpr); 5691 }); 5692 }; 5693 if ((*IPriv)->getType()->isArrayType()) { 5694 // Emit atomic reduction for array section. 5695 const auto *RHSVar = 5696 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 5697 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), VD, RHSVar, 5698 AtomicRedGen, XExpr, EExpr, UpExpr); 5699 } else { 5700 // Emit atomic reduction for array subscript or single variable. 5701 AtomicRedGen(CGF, XExpr, EExpr, UpExpr); 5702 } 5703 } else { 5704 // Emit as a critical region. 5705 auto &&CritRedGen = [E, Loc](CodeGenFunction &CGF, const Expr *, 5706 const Expr *, const Expr *) { 5707 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 5708 std::string Name = RT.getName({"atomic_reduction"}); 5709 RT.emitCriticalRegion( 5710 CGF, Name, 5711 [=](CodeGenFunction &CGF, PrePostActionTy &Action) { 5712 Action.Enter(CGF); 5713 emitReductionCombiner(CGF, E); 5714 }, 5715 Loc); 5716 }; 5717 if ((*IPriv)->getType()->isArrayType()) { 5718 const auto *LHSVar = 5719 cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 5720 const auto *RHSVar = 5721 cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 5722 EmitOMPAggregateReduction(CGF, (*IPriv)->getType(), LHSVar, RHSVar, 5723 CritRedGen); 5724 } else { 5725 CritRedGen(CGF, nullptr, nullptr, nullptr); 5726 } 5727 } 5728 ++ILHS; 5729 ++IRHS; 5730 ++IPriv; 5731 } 5732 }; 5733 RegionCodeGenTy AtomicRCG(AtomicCodeGen); 5734 if (!WithNowait) { 5735 // Add emission of __kmpc_end_reduce(<loc>, <gtid>, &<lock>); 5736 llvm::Value *EndArgs[] = { 5737 IdentTLoc, // ident_t *<loc> 5738 ThreadId, // i32 <gtid> 5739 Lock // kmp_critical_name *&<lock> 5740 }; 5741 CommonActionTy Action(nullptr, llvm::None, 5742 createRuntimeFunction(OMPRTL__kmpc_end_reduce), 5743 EndArgs); 5744 AtomicRCG.setAction(Action); 5745 AtomicRCG(CGF); 5746 } else { 5747 AtomicRCG(CGF); 5748 } 5749 5750 CGF.EmitBranch(DefaultBB); 5751 CGF.EmitBlock(DefaultBB, /*IsFinished=*/true); 5752 } 5753 5754 /// Generates unique name for artificial threadprivate variables. 5755 /// Format is: <Prefix> "." <Decl_mangled_name> "_" "<Decl_start_loc_raw_enc>" 5756 static std::string generateUniqueName(CodeGenModule &CGM, StringRef Prefix, 5757 const Expr *Ref) { 5758 SmallString<256> Buffer; 5759 llvm::raw_svector_ostream Out(Buffer); 5760 const clang::DeclRefExpr *DE; 5761 const VarDecl *D = ::getBaseDecl(Ref, DE); 5762 if (!D) 5763 D = cast<VarDecl>(cast<DeclRefExpr>(Ref)->getDecl()); 5764 D = D->getCanonicalDecl(); 5765 std::string Name = CGM.getOpenMPRuntime().getName( 5766 {D->isLocalVarDeclOrParm() ? D->getName() : CGM.getMangledName(D)}); 5767 Out << Prefix << Name << "_" 5768 << D->getCanonicalDecl()->getBeginLoc().getRawEncoding(); 5769 return Out.str(); 5770 } 5771 5772 /// Emits reduction initializer function: 5773 /// \code 5774 /// void @.red_init(void* %arg) { 5775 /// %0 = bitcast void* %arg to <type>* 5776 /// store <type> <init>, <type>* %0 5777 /// ret void 5778 /// } 5779 /// \endcode 5780 static llvm::Value *emitReduceInitFunction(CodeGenModule &CGM, 5781 SourceLocation Loc, 5782 ReductionCodeGen &RCG, unsigned N) { 5783 ASTContext &C = CGM.getContext(); 5784 FunctionArgList Args; 5785 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5786 ImplicitParamDecl::Other); 5787 Args.emplace_back(&Param); 5788 const auto &FnInfo = 5789 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 5790 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 5791 std::string Name = CGM.getOpenMPRuntime().getName({"red_init", ""}); 5792 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 5793 Name, &CGM.getModule()); 5794 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 5795 Fn->setDoesNotRecurse(); 5796 CodeGenFunction CGF(CGM); 5797 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); 5798 Address PrivateAddr = CGF.EmitLoadOfPointer( 5799 CGF.GetAddrOfLocalVar(&Param), 5800 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 5801 llvm::Value *Size = nullptr; 5802 // If the size of the reduction item is non-constant, load it from global 5803 // threadprivate variable. 5804 if (RCG.getSizes(N).second) { 5805 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 5806 CGF, CGM.getContext().getSizeType(), 5807 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 5808 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, 5809 CGM.getContext().getSizeType(), Loc); 5810 } 5811 RCG.emitAggregateType(CGF, N, Size); 5812 LValue SharedLVal; 5813 // If initializer uses initializer from declare reduction construct, emit a 5814 // pointer to the address of the original reduction item (reuired by reduction 5815 // initializer) 5816 if (RCG.usesReductionInitializer(N)) { 5817 Address SharedAddr = 5818 CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 5819 CGF, CGM.getContext().VoidPtrTy, 5820 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N))); 5821 SharedAddr = CGF.EmitLoadOfPointer( 5822 SharedAddr, 5823 CGM.getContext().VoidPtrTy.castAs<PointerType>()->getTypePtr()); 5824 SharedLVal = CGF.MakeAddrLValue(SharedAddr, CGM.getContext().VoidPtrTy); 5825 } else { 5826 SharedLVal = CGF.MakeNaturalAlignAddrLValue( 5827 llvm::ConstantPointerNull::get(CGM.VoidPtrTy), 5828 CGM.getContext().VoidPtrTy); 5829 } 5830 // Emit the initializer: 5831 // %0 = bitcast void* %arg to <type>* 5832 // store <type> <init>, <type>* %0 5833 RCG.emitInitialization(CGF, N, PrivateAddr, SharedLVal, 5834 [](CodeGenFunction &) { return false; }); 5835 CGF.FinishFunction(); 5836 return Fn; 5837 } 5838 5839 /// Emits reduction combiner function: 5840 /// \code 5841 /// void @.red_comb(void* %arg0, void* %arg1) { 5842 /// %lhs = bitcast void* %arg0 to <type>* 5843 /// %rhs = bitcast void* %arg1 to <type>* 5844 /// %2 = <ReductionOp>(<type>* %lhs, <type>* %rhs) 5845 /// store <type> %2, <type>* %lhs 5846 /// ret void 5847 /// } 5848 /// \endcode 5849 static llvm::Value *emitReduceCombFunction(CodeGenModule &CGM, 5850 SourceLocation Loc, 5851 ReductionCodeGen &RCG, unsigned N, 5852 const Expr *ReductionOp, 5853 const Expr *LHS, const Expr *RHS, 5854 const Expr *PrivateRef) { 5855 ASTContext &C = CGM.getContext(); 5856 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(LHS)->getDecl()); 5857 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(RHS)->getDecl()); 5858 FunctionArgList Args; 5859 ImplicitParamDecl ParamInOut(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, 5860 C.VoidPtrTy, ImplicitParamDecl::Other); 5861 ImplicitParamDecl ParamIn(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5862 ImplicitParamDecl::Other); 5863 Args.emplace_back(&ParamInOut); 5864 Args.emplace_back(&ParamIn); 5865 const auto &FnInfo = 5866 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 5867 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 5868 std::string Name = CGM.getOpenMPRuntime().getName({"red_comb", ""}); 5869 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 5870 Name, &CGM.getModule()); 5871 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 5872 Fn->setDoesNotRecurse(); 5873 CodeGenFunction CGF(CGM); 5874 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); 5875 llvm::Value *Size = nullptr; 5876 // If the size of the reduction item is non-constant, load it from global 5877 // threadprivate variable. 5878 if (RCG.getSizes(N).second) { 5879 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 5880 CGF, CGM.getContext().getSizeType(), 5881 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 5882 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, 5883 CGM.getContext().getSizeType(), Loc); 5884 } 5885 RCG.emitAggregateType(CGF, N, Size); 5886 // Remap lhs and rhs variables to the addresses of the function arguments. 5887 // %lhs = bitcast void* %arg0 to <type>* 5888 // %rhs = bitcast void* %arg1 to <type>* 5889 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5890 PrivateScope.addPrivate(LHSVD, [&C, &CGF, &ParamInOut, LHSVD]() { 5891 // Pull out the pointer to the variable. 5892 Address PtrAddr = CGF.EmitLoadOfPointer( 5893 CGF.GetAddrOfLocalVar(&ParamInOut), 5894 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 5895 return CGF.Builder.CreateElementBitCast( 5896 PtrAddr, CGF.ConvertTypeForMem(LHSVD->getType())); 5897 }); 5898 PrivateScope.addPrivate(RHSVD, [&C, &CGF, &ParamIn, RHSVD]() { 5899 // Pull out the pointer to the variable. 5900 Address PtrAddr = CGF.EmitLoadOfPointer( 5901 CGF.GetAddrOfLocalVar(&ParamIn), 5902 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 5903 return CGF.Builder.CreateElementBitCast( 5904 PtrAddr, CGF.ConvertTypeForMem(RHSVD->getType())); 5905 }); 5906 PrivateScope.Privatize(); 5907 // Emit the combiner body: 5908 // %2 = <ReductionOp>(<type> *%lhs, <type> *%rhs) 5909 // store <type> %2, <type>* %lhs 5910 CGM.getOpenMPRuntime().emitSingleReductionCombiner( 5911 CGF, ReductionOp, PrivateRef, cast<DeclRefExpr>(LHS), 5912 cast<DeclRefExpr>(RHS)); 5913 CGF.FinishFunction(); 5914 return Fn; 5915 } 5916 5917 /// Emits reduction finalizer function: 5918 /// \code 5919 /// void @.red_fini(void* %arg) { 5920 /// %0 = bitcast void* %arg to <type>* 5921 /// <destroy>(<type>* %0) 5922 /// ret void 5923 /// } 5924 /// \endcode 5925 static llvm::Value *emitReduceFiniFunction(CodeGenModule &CGM, 5926 SourceLocation Loc, 5927 ReductionCodeGen &RCG, unsigned N) { 5928 if (!RCG.needCleanups(N)) 5929 return nullptr; 5930 ASTContext &C = CGM.getContext(); 5931 FunctionArgList Args; 5932 ImplicitParamDecl Param(C, /*DC=*/nullptr, Loc, /*Id=*/nullptr, C.VoidPtrTy, 5933 ImplicitParamDecl::Other); 5934 Args.emplace_back(&Param); 5935 const auto &FnInfo = 5936 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, Args); 5937 llvm::FunctionType *FnTy = CGM.getTypes().GetFunctionType(FnInfo); 5938 std::string Name = CGM.getOpenMPRuntime().getName({"red_fini", ""}); 5939 auto *Fn = llvm::Function::Create(FnTy, llvm::GlobalValue::InternalLinkage, 5940 Name, &CGM.getModule()); 5941 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FnInfo); 5942 Fn->setDoesNotRecurse(); 5943 CodeGenFunction CGF(CGM); 5944 CGF.StartFunction(GlobalDecl(), C.VoidTy, Fn, FnInfo, Args, Loc, Loc); 5945 Address PrivateAddr = CGF.EmitLoadOfPointer( 5946 CGF.GetAddrOfLocalVar(&Param), 5947 C.getPointerType(C.VoidPtrTy).castAs<PointerType>()); 5948 llvm::Value *Size = nullptr; 5949 // If the size of the reduction item is non-constant, load it from global 5950 // threadprivate variable. 5951 if (RCG.getSizes(N).second) { 5952 Address SizeAddr = CGM.getOpenMPRuntime().getAddrOfArtificialThreadPrivate( 5953 CGF, CGM.getContext().getSizeType(), 5954 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 5955 Size = CGF.EmitLoadOfScalar(SizeAddr, /*Volatile=*/false, 5956 CGM.getContext().getSizeType(), Loc); 5957 } 5958 RCG.emitAggregateType(CGF, N, Size); 5959 // Emit the finalizer body: 5960 // <destroy>(<type>* %0) 5961 RCG.emitCleanups(CGF, N, PrivateAddr); 5962 CGF.FinishFunction(); 5963 return Fn; 5964 } 5965 5966 llvm::Value *CGOpenMPRuntime::emitTaskReductionInit( 5967 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, 5968 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) { 5969 if (!CGF.HaveInsertPoint() || Data.ReductionVars.empty()) 5970 return nullptr; 5971 5972 // Build typedef struct: 5973 // kmp_task_red_input { 5974 // void *reduce_shar; // shared reduction item 5975 // size_t reduce_size; // size of data item 5976 // void *reduce_init; // data initialization routine 5977 // void *reduce_fini; // data finalization routine 5978 // void *reduce_comb; // data combiner routine 5979 // kmp_task_red_flags_t flags; // flags for additional info from compiler 5980 // } kmp_task_red_input_t; 5981 ASTContext &C = CGM.getContext(); 5982 RecordDecl *RD = C.buildImplicitRecord("kmp_task_red_input_t"); 5983 RD->startDefinition(); 5984 const FieldDecl *SharedFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 5985 const FieldDecl *SizeFD = addFieldToRecordDecl(C, RD, C.getSizeType()); 5986 const FieldDecl *InitFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 5987 const FieldDecl *FiniFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 5988 const FieldDecl *CombFD = addFieldToRecordDecl(C, RD, C.VoidPtrTy); 5989 const FieldDecl *FlagsFD = addFieldToRecordDecl( 5990 C, RD, C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/false)); 5991 RD->completeDefinition(); 5992 QualType RDType = C.getRecordType(RD); 5993 unsigned Size = Data.ReductionVars.size(); 5994 llvm::APInt ArraySize(/*numBits=*/64, Size); 5995 QualType ArrayRDType = C.getConstantArrayType( 5996 RDType, ArraySize, ArrayType::Normal, /*IndexTypeQuals=*/0); 5997 // kmp_task_red_input_t .rd_input.[Size]; 5998 Address TaskRedInput = CGF.CreateMemTemp(ArrayRDType, ".rd_input."); 5999 ReductionCodeGen RCG(Data.ReductionVars, Data.ReductionCopies, 6000 Data.ReductionOps); 6001 for (unsigned Cnt = 0; Cnt < Size; ++Cnt) { 6002 // kmp_task_red_input_t &ElemLVal = .rd_input.[Cnt]; 6003 llvm::Value *Idxs[] = {llvm::ConstantInt::get(CGM.SizeTy, /*V=*/0), 6004 llvm::ConstantInt::get(CGM.SizeTy, Cnt)}; 6005 llvm::Value *GEP = CGF.EmitCheckedInBoundsGEP( 6006 TaskRedInput.getPointer(), Idxs, 6007 /*SignedIndices=*/false, /*IsSubtraction=*/false, Loc, 6008 ".rd_input.gep."); 6009 LValue ElemLVal = CGF.MakeNaturalAlignAddrLValue(GEP, RDType); 6010 // ElemLVal.reduce_shar = &Shareds[Cnt]; 6011 LValue SharedLVal = CGF.EmitLValueForField(ElemLVal, SharedFD); 6012 RCG.emitSharedLValue(CGF, Cnt); 6013 llvm::Value *CastedShared = 6014 CGF.EmitCastToVoidPtr(RCG.getSharedLValue(Cnt).getPointer()); 6015 CGF.EmitStoreOfScalar(CastedShared, SharedLVal); 6016 RCG.emitAggregateType(CGF, Cnt); 6017 llvm::Value *SizeValInChars; 6018 llvm::Value *SizeVal; 6019 std::tie(SizeValInChars, SizeVal) = RCG.getSizes(Cnt); 6020 // We use delayed creation/initialization for VLAs, array sections and 6021 // custom reduction initializations. It is required because runtime does not 6022 // provide the way to pass the sizes of VLAs/array sections to 6023 // initializer/combiner/finalizer functions and does not pass the pointer to 6024 // original reduction item to the initializer. Instead threadprivate global 6025 // variables are used to store these values and use them in the functions. 6026 bool DelayedCreation = !!SizeVal; 6027 SizeValInChars = CGF.Builder.CreateIntCast(SizeValInChars, CGM.SizeTy, 6028 /*isSigned=*/false); 6029 LValue SizeLVal = CGF.EmitLValueForField(ElemLVal, SizeFD); 6030 CGF.EmitStoreOfScalar(SizeValInChars, SizeLVal); 6031 // ElemLVal.reduce_init = init; 6032 LValue InitLVal = CGF.EmitLValueForField(ElemLVal, InitFD); 6033 llvm::Value *InitAddr = 6034 CGF.EmitCastToVoidPtr(emitReduceInitFunction(CGM, Loc, RCG, Cnt)); 6035 CGF.EmitStoreOfScalar(InitAddr, InitLVal); 6036 DelayedCreation = DelayedCreation || RCG.usesReductionInitializer(Cnt); 6037 // ElemLVal.reduce_fini = fini; 6038 LValue FiniLVal = CGF.EmitLValueForField(ElemLVal, FiniFD); 6039 llvm::Value *Fini = emitReduceFiniFunction(CGM, Loc, RCG, Cnt); 6040 llvm::Value *FiniAddr = Fini 6041 ? CGF.EmitCastToVoidPtr(Fini) 6042 : llvm::ConstantPointerNull::get(CGM.VoidPtrTy); 6043 CGF.EmitStoreOfScalar(FiniAddr, FiniLVal); 6044 // ElemLVal.reduce_comb = comb; 6045 LValue CombLVal = CGF.EmitLValueForField(ElemLVal, CombFD); 6046 llvm::Value *CombAddr = CGF.EmitCastToVoidPtr(emitReduceCombFunction( 6047 CGM, Loc, RCG, Cnt, Data.ReductionOps[Cnt], LHSExprs[Cnt], 6048 RHSExprs[Cnt], Data.ReductionCopies[Cnt])); 6049 CGF.EmitStoreOfScalar(CombAddr, CombLVal); 6050 // ElemLVal.flags = 0; 6051 LValue FlagsLVal = CGF.EmitLValueForField(ElemLVal, FlagsFD); 6052 if (DelayedCreation) { 6053 CGF.EmitStoreOfScalar( 6054 llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/1, /*IsSigned=*/true), 6055 FlagsLVal); 6056 } else 6057 CGF.EmitNullInitialization(FlagsLVal.getAddress(), FlagsLVal.getType()); 6058 } 6059 // Build call void *__kmpc_task_reduction_init(int gtid, int num_data, void 6060 // *data); 6061 llvm::Value *Args[] = { 6062 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy, 6063 /*isSigned=*/true), 6064 llvm::ConstantInt::get(CGM.IntTy, Size, /*isSigned=*/true), 6065 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(TaskRedInput.getPointer(), 6066 CGM.VoidPtrTy)}; 6067 return CGF.EmitRuntimeCall( 6068 createRuntimeFunction(OMPRTL__kmpc_task_reduction_init), Args); 6069 } 6070 6071 void CGOpenMPRuntime::emitTaskReductionFixups(CodeGenFunction &CGF, 6072 SourceLocation Loc, 6073 ReductionCodeGen &RCG, 6074 unsigned N) { 6075 auto Sizes = RCG.getSizes(N); 6076 // Emit threadprivate global variable if the type is non-constant 6077 // (Sizes.second = nullptr). 6078 if (Sizes.second) { 6079 llvm::Value *SizeVal = CGF.Builder.CreateIntCast(Sizes.second, CGM.SizeTy, 6080 /*isSigned=*/false); 6081 Address SizeAddr = getAddrOfArtificialThreadPrivate( 6082 CGF, CGM.getContext().getSizeType(), 6083 generateUniqueName(CGM, "reduction_size", RCG.getRefExpr(N))); 6084 CGF.Builder.CreateStore(SizeVal, SizeAddr, /*IsVolatile=*/false); 6085 } 6086 // Store address of the original reduction item if custom initializer is used. 6087 if (RCG.usesReductionInitializer(N)) { 6088 Address SharedAddr = getAddrOfArtificialThreadPrivate( 6089 CGF, CGM.getContext().VoidPtrTy, 6090 generateUniqueName(CGM, "reduction", RCG.getRefExpr(N))); 6091 CGF.Builder.CreateStore( 6092 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 6093 RCG.getSharedLValue(N).getPointer(), CGM.VoidPtrTy), 6094 SharedAddr, /*IsVolatile=*/false); 6095 } 6096 } 6097 6098 Address CGOpenMPRuntime::getTaskReductionItem(CodeGenFunction &CGF, 6099 SourceLocation Loc, 6100 llvm::Value *ReductionsPtr, 6101 LValue SharedLVal) { 6102 // Build call void *__kmpc_task_reduction_get_th_data(int gtid, void *tg, void 6103 // *d); 6104 llvm::Value *Args[] = { 6105 CGF.Builder.CreateIntCast(getThreadID(CGF, Loc), CGM.IntTy, 6106 /*isSigned=*/true), 6107 ReductionsPtr, 6108 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(SharedLVal.getPointer(), 6109 CGM.VoidPtrTy)}; 6110 return Address( 6111 CGF.EmitRuntimeCall( 6112 createRuntimeFunction(OMPRTL__kmpc_task_reduction_get_th_data), Args), 6113 SharedLVal.getAlignment()); 6114 } 6115 6116 void CGOpenMPRuntime::emitTaskwaitCall(CodeGenFunction &CGF, 6117 SourceLocation Loc) { 6118 if (!CGF.HaveInsertPoint()) 6119 return; 6120 // Build call kmp_int32 __kmpc_omp_taskwait(ident_t *loc, kmp_int32 6121 // global_tid); 6122 llvm::Value *Args[] = {emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc)}; 6123 // Ignore return result until untied tasks are supported. 6124 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_omp_taskwait), Args); 6125 if (auto *Region = dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) 6126 Region->emitUntiedSwitch(CGF); 6127 } 6128 6129 void CGOpenMPRuntime::emitInlinedDirective(CodeGenFunction &CGF, 6130 OpenMPDirectiveKind InnerKind, 6131 const RegionCodeGenTy &CodeGen, 6132 bool HasCancel) { 6133 if (!CGF.HaveInsertPoint()) 6134 return; 6135 InlinedOpenMPRegionRAII Region(CGF, CodeGen, InnerKind, HasCancel); 6136 CGF.CapturedStmtInfo->EmitBody(CGF, /*S=*/nullptr); 6137 } 6138 6139 namespace { 6140 enum RTCancelKind { 6141 CancelNoreq = 0, 6142 CancelParallel = 1, 6143 CancelLoop = 2, 6144 CancelSections = 3, 6145 CancelTaskgroup = 4 6146 }; 6147 } // anonymous namespace 6148 6149 static RTCancelKind getCancellationKind(OpenMPDirectiveKind CancelRegion) { 6150 RTCancelKind CancelKind = CancelNoreq; 6151 if (CancelRegion == OMPD_parallel) 6152 CancelKind = CancelParallel; 6153 else if (CancelRegion == OMPD_for) 6154 CancelKind = CancelLoop; 6155 else if (CancelRegion == OMPD_sections) 6156 CancelKind = CancelSections; 6157 else { 6158 assert(CancelRegion == OMPD_taskgroup); 6159 CancelKind = CancelTaskgroup; 6160 } 6161 return CancelKind; 6162 } 6163 6164 void CGOpenMPRuntime::emitCancellationPointCall( 6165 CodeGenFunction &CGF, SourceLocation Loc, 6166 OpenMPDirectiveKind CancelRegion) { 6167 if (!CGF.HaveInsertPoint()) 6168 return; 6169 // Build call kmp_int32 __kmpc_cancellationpoint(ident_t *loc, kmp_int32 6170 // global_tid, kmp_int32 cncl_kind); 6171 if (auto *OMPRegionInfo = 6172 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 6173 // For 'cancellation point taskgroup', the task region info may not have a 6174 // cancel. This may instead happen in another adjacent task. 6175 if (CancelRegion == OMPD_taskgroup || OMPRegionInfo->hasCancel()) { 6176 llvm::Value *Args[] = { 6177 emitUpdateLocation(CGF, Loc), getThreadID(CGF, Loc), 6178 CGF.Builder.getInt32(getCancellationKind(CancelRegion))}; 6179 // Ignore return result until untied tasks are supported. 6180 llvm::Value *Result = CGF.EmitRuntimeCall( 6181 createRuntimeFunction(OMPRTL__kmpc_cancellationpoint), Args); 6182 // if (__kmpc_cancellationpoint()) { 6183 // exit from construct; 6184 // } 6185 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); 6186 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); 6187 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); 6188 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); 6189 CGF.EmitBlock(ExitBB); 6190 // exit from construct; 6191 CodeGenFunction::JumpDest CancelDest = 6192 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); 6193 CGF.EmitBranchThroughCleanup(CancelDest); 6194 CGF.EmitBlock(ContBB, /*IsFinished=*/true); 6195 } 6196 } 6197 } 6198 6199 void CGOpenMPRuntime::emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, 6200 const Expr *IfCond, 6201 OpenMPDirectiveKind CancelRegion) { 6202 if (!CGF.HaveInsertPoint()) 6203 return; 6204 // Build call kmp_int32 __kmpc_cancel(ident_t *loc, kmp_int32 global_tid, 6205 // kmp_int32 cncl_kind); 6206 if (auto *OMPRegionInfo = 6207 dyn_cast_or_null<CGOpenMPRegionInfo>(CGF.CapturedStmtInfo)) { 6208 auto &&ThenGen = [Loc, CancelRegion, OMPRegionInfo](CodeGenFunction &CGF, 6209 PrePostActionTy &) { 6210 CGOpenMPRuntime &RT = CGF.CGM.getOpenMPRuntime(); 6211 llvm::Value *Args[] = { 6212 RT.emitUpdateLocation(CGF, Loc), RT.getThreadID(CGF, Loc), 6213 CGF.Builder.getInt32(getCancellationKind(CancelRegion))}; 6214 // Ignore return result until untied tasks are supported. 6215 llvm::Value *Result = CGF.EmitRuntimeCall( 6216 RT.createRuntimeFunction(OMPRTL__kmpc_cancel), Args); 6217 // if (__kmpc_cancel()) { 6218 // exit from construct; 6219 // } 6220 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".cancel.exit"); 6221 llvm::BasicBlock *ContBB = CGF.createBasicBlock(".cancel.continue"); 6222 llvm::Value *Cmp = CGF.Builder.CreateIsNotNull(Result); 6223 CGF.Builder.CreateCondBr(Cmp, ExitBB, ContBB); 6224 CGF.EmitBlock(ExitBB); 6225 // exit from construct; 6226 CodeGenFunction::JumpDest CancelDest = 6227 CGF.getOMPCancelDestination(OMPRegionInfo->getDirectiveKind()); 6228 CGF.EmitBranchThroughCleanup(CancelDest); 6229 CGF.EmitBlock(ContBB, /*IsFinished=*/true); 6230 }; 6231 if (IfCond) { 6232 emitOMPIfClause(CGF, IfCond, ThenGen, 6233 [](CodeGenFunction &, PrePostActionTy &) {}); 6234 } else { 6235 RegionCodeGenTy ThenRCG(ThenGen); 6236 ThenRCG(CGF); 6237 } 6238 } 6239 } 6240 6241 void CGOpenMPRuntime::emitTargetOutlinedFunction( 6242 const OMPExecutableDirective &D, StringRef ParentName, 6243 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, 6244 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { 6245 assert(!ParentName.empty() && "Invalid target region parent name!"); 6246 emitTargetOutlinedFunctionHelper(D, ParentName, OutlinedFn, OutlinedFnID, 6247 IsOffloadEntry, CodeGen); 6248 } 6249 6250 void CGOpenMPRuntime::emitTargetOutlinedFunctionHelper( 6251 const OMPExecutableDirective &D, StringRef ParentName, 6252 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, 6253 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { 6254 // Create a unique name for the entry function using the source location 6255 // information of the current target region. The name will be something like: 6256 // 6257 // __omp_offloading_DD_FFFF_PP_lBB 6258 // 6259 // where DD_FFFF is an ID unique to the file (device and file IDs), PP is the 6260 // mangled name of the function that encloses the target region and BB is the 6261 // line number of the target region. 6262 6263 unsigned DeviceID; 6264 unsigned FileID; 6265 unsigned Line; 6266 getTargetEntryUniqueInfo(CGM.getContext(), D.getBeginLoc(), DeviceID, FileID, 6267 Line); 6268 SmallString<64> EntryFnName; 6269 { 6270 llvm::raw_svector_ostream OS(EntryFnName); 6271 OS << "__omp_offloading" << llvm::format("_%x", DeviceID) 6272 << llvm::format("_%x_", FileID) << ParentName << "_l" << Line; 6273 } 6274 6275 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 6276 6277 CodeGenFunction CGF(CGM, true); 6278 CGOpenMPTargetRegionInfo CGInfo(CS, CodeGen, EntryFnName); 6279 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 6280 6281 OutlinedFn = CGF.GenerateOpenMPCapturedStmtFunction(CS); 6282 6283 // If this target outline function is not an offload entry, we don't need to 6284 // register it. 6285 if (!IsOffloadEntry) 6286 return; 6287 6288 // The target region ID is used by the runtime library to identify the current 6289 // target region, so it only has to be unique and not necessarily point to 6290 // anything. It could be the pointer to the outlined function that implements 6291 // the target region, but we aren't using that so that the compiler doesn't 6292 // need to keep that, and could therefore inline the host function if proven 6293 // worthwhile during optimization. In the other hand, if emitting code for the 6294 // device, the ID has to be the function address so that it can retrieved from 6295 // the offloading entry and launched by the runtime library. We also mark the 6296 // outlined function to have external linkage in case we are emitting code for 6297 // the device, because these functions will be entry points to the device. 6298 6299 if (CGM.getLangOpts().OpenMPIsDevice) { 6300 OutlinedFnID = llvm::ConstantExpr::getBitCast(OutlinedFn, CGM.Int8PtrTy); 6301 OutlinedFn->setLinkage(llvm::GlobalValue::WeakAnyLinkage); 6302 OutlinedFn->setDSOLocal(false); 6303 } else { 6304 std::string Name = getName({EntryFnName, "region_id"}); 6305 OutlinedFnID = new llvm::GlobalVariable( 6306 CGM.getModule(), CGM.Int8Ty, /*isConstant=*/true, 6307 llvm::GlobalValue::WeakAnyLinkage, 6308 llvm::Constant::getNullValue(CGM.Int8Ty), Name); 6309 } 6310 6311 // Register the information for the entry associated with this target region. 6312 OffloadEntriesInfoManager.registerTargetRegionEntryInfo( 6313 DeviceID, FileID, ParentName, Line, OutlinedFn, OutlinedFnID, 6314 OffloadEntriesInfoManagerTy::OMPTargetRegionEntryTargetRegion); 6315 } 6316 6317 /// discard all CompoundStmts intervening between two constructs 6318 static const Stmt *ignoreCompoundStmts(const Stmt *Body) { 6319 while (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) 6320 Body = CS->body_front(); 6321 6322 return Body; 6323 } 6324 6325 /// Emit the number of teams for a target directive. Inspect the num_teams 6326 /// clause associated with a teams construct combined or closely nested 6327 /// with the target directive. 6328 /// 6329 /// Emit a team of size one for directives such as 'target parallel' that 6330 /// have no associated teams construct. 6331 /// 6332 /// Otherwise, return nullptr. 6333 static llvm::Value * 6334 emitNumTeamsForTargetDirective(CGOpenMPRuntime &OMPRuntime, 6335 CodeGenFunction &CGF, 6336 const OMPExecutableDirective &D) { 6337 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the " 6338 "teams directive expected to be " 6339 "emitted only for the host!"); 6340 6341 CGBuilderTy &Bld = CGF.Builder; 6342 6343 // If the target directive is combined with a teams directive: 6344 // Return the value in the num_teams clause, if any. 6345 // Otherwise, return 0 to denote the runtime default. 6346 if (isOpenMPTeamsDirective(D.getDirectiveKind())) { 6347 if (const auto *NumTeamsClause = D.getSingleClause<OMPNumTeamsClause>()) { 6348 CodeGenFunction::RunCleanupsScope NumTeamsScope(CGF); 6349 llvm::Value *NumTeams = CGF.EmitScalarExpr(NumTeamsClause->getNumTeams(), 6350 /*IgnoreResultAssign*/ true); 6351 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty, 6352 /*IsSigned=*/true); 6353 } 6354 6355 // The default value is 0. 6356 return Bld.getInt32(0); 6357 } 6358 6359 // If the target directive is combined with a parallel directive but not a 6360 // teams directive, start one team. 6361 if (isOpenMPParallelDirective(D.getDirectiveKind())) 6362 return Bld.getInt32(1); 6363 6364 // If the current target region has a teams region enclosed, we need to get 6365 // the number of teams to pass to the runtime function call. This is done 6366 // by generating the expression in a inlined region. This is required because 6367 // the expression is captured in the enclosing target environment when the 6368 // teams directive is not combined with target. 6369 6370 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 6371 6372 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>( 6373 ignoreCompoundStmts(CS.getCapturedStmt()))) { 6374 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) { 6375 if (const auto *NTE = TeamsDir->getSingleClause<OMPNumTeamsClause>()) { 6376 CGOpenMPInnerExprInfo CGInfo(CGF, CS); 6377 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 6378 llvm::Value *NumTeams = CGF.EmitScalarExpr(NTE->getNumTeams()); 6379 return Bld.CreateIntCast(NumTeams, CGF.Int32Ty, 6380 /*IsSigned=*/true); 6381 } 6382 6383 // If we have an enclosed teams directive but no num_teams clause we use 6384 // the default value 0. 6385 return Bld.getInt32(0); 6386 } 6387 } 6388 6389 // No teams associated with the directive. 6390 return nullptr; 6391 } 6392 6393 /// Emit the number of threads for a target directive. Inspect the 6394 /// thread_limit clause associated with a teams construct combined or closely 6395 /// nested with the target directive. 6396 /// 6397 /// Emit the num_threads clause for directives such as 'target parallel' that 6398 /// have no associated teams construct. 6399 /// 6400 /// Otherwise, return nullptr. 6401 static llvm::Value * 6402 emitNumThreadsForTargetDirective(CGOpenMPRuntime &OMPRuntime, 6403 CodeGenFunction &CGF, 6404 const OMPExecutableDirective &D) { 6405 assert(!CGF.getLangOpts().OpenMPIsDevice && "Clauses associated with the " 6406 "teams directive expected to be " 6407 "emitted only for the host!"); 6408 6409 CGBuilderTy &Bld = CGF.Builder; 6410 6411 // 6412 // If the target directive is combined with a teams directive: 6413 // Return the value in the thread_limit clause, if any. 6414 // 6415 // If the target directive is combined with a parallel directive: 6416 // Return the value in the num_threads clause, if any. 6417 // 6418 // If both clauses are set, select the minimum of the two. 6419 // 6420 // If neither teams or parallel combined directives set the number of threads 6421 // in a team, return 0 to denote the runtime default. 6422 // 6423 // If this is not a teams directive return nullptr. 6424 6425 if (isOpenMPTeamsDirective(D.getDirectiveKind()) || 6426 isOpenMPParallelDirective(D.getDirectiveKind())) { 6427 llvm::Value *DefaultThreadLimitVal = Bld.getInt32(0); 6428 llvm::Value *NumThreadsVal = nullptr; 6429 llvm::Value *ThreadLimitVal = nullptr; 6430 6431 if (const auto *ThreadLimitClause = 6432 D.getSingleClause<OMPThreadLimitClause>()) { 6433 CodeGenFunction::RunCleanupsScope ThreadLimitScope(CGF); 6434 llvm::Value *ThreadLimit = 6435 CGF.EmitScalarExpr(ThreadLimitClause->getThreadLimit(), 6436 /*IgnoreResultAssign*/ true); 6437 ThreadLimitVal = Bld.CreateIntCast(ThreadLimit, CGF.Int32Ty, 6438 /*IsSigned=*/true); 6439 } 6440 6441 if (const auto *NumThreadsClause = 6442 D.getSingleClause<OMPNumThreadsClause>()) { 6443 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 6444 llvm::Value *NumThreads = 6445 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 6446 /*IgnoreResultAssign*/ true); 6447 NumThreadsVal = 6448 Bld.CreateIntCast(NumThreads, CGF.Int32Ty, /*IsSigned=*/true); 6449 } 6450 6451 // Select the lesser of thread_limit and num_threads. 6452 if (NumThreadsVal) 6453 ThreadLimitVal = ThreadLimitVal 6454 ? Bld.CreateSelect(Bld.CreateICmpSLT(NumThreadsVal, 6455 ThreadLimitVal), 6456 NumThreadsVal, ThreadLimitVal) 6457 : NumThreadsVal; 6458 6459 // Set default value passed to the runtime if either teams or a target 6460 // parallel type directive is found but no clause is specified. 6461 if (!ThreadLimitVal) 6462 ThreadLimitVal = DefaultThreadLimitVal; 6463 6464 return ThreadLimitVal; 6465 } 6466 6467 // If the current target region has a teams region enclosed, we need to get 6468 // the thread limit to pass to the runtime function call. This is done 6469 // by generating the expression in a inlined region. This is required because 6470 // the expression is captured in the enclosing target environment when the 6471 // teams directive is not combined with target. 6472 6473 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 6474 6475 if (const auto *TeamsDir = dyn_cast_or_null<OMPExecutableDirective>( 6476 ignoreCompoundStmts(CS.getCapturedStmt()))) { 6477 if (isOpenMPTeamsDirective(TeamsDir->getDirectiveKind())) { 6478 if (const auto *TLE = TeamsDir->getSingleClause<OMPThreadLimitClause>()) { 6479 CGOpenMPInnerExprInfo CGInfo(CGF, CS); 6480 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGInfo); 6481 llvm::Value *ThreadLimit = CGF.EmitScalarExpr(TLE->getThreadLimit()); 6482 return CGF.Builder.CreateIntCast(ThreadLimit, CGF.Int32Ty, 6483 /*IsSigned=*/true); 6484 } 6485 6486 // If we have an enclosed teams directive but no thread_limit clause we 6487 // use the default value 0. 6488 return CGF.Builder.getInt32(0); 6489 } 6490 } 6491 6492 // No teams associated with the directive. 6493 return nullptr; 6494 } 6495 6496 namespace { 6497 LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE(); 6498 6499 // Utility to handle information from clauses associated with a given 6500 // construct that use mappable expressions (e.g. 'map' clause, 'to' clause). 6501 // It provides a convenient interface to obtain the information and generate 6502 // code for that information. 6503 class MappableExprsHandler { 6504 public: 6505 /// Values for bit flags used to specify the mapping type for 6506 /// offloading. 6507 enum OpenMPOffloadMappingFlags : uint64_t { 6508 /// No flags 6509 OMP_MAP_NONE = 0x0, 6510 /// Allocate memory on the device and move data from host to device. 6511 OMP_MAP_TO = 0x01, 6512 /// Allocate memory on the device and move data from device to host. 6513 OMP_MAP_FROM = 0x02, 6514 /// Always perform the requested mapping action on the element, even 6515 /// if it was already mapped before. 6516 OMP_MAP_ALWAYS = 0x04, 6517 /// Delete the element from the device environment, ignoring the 6518 /// current reference count associated with the element. 6519 OMP_MAP_DELETE = 0x08, 6520 /// The element being mapped is a pointer-pointee pair; both the 6521 /// pointer and the pointee should be mapped. 6522 OMP_MAP_PTR_AND_OBJ = 0x10, 6523 /// This flags signals that the base address of an entry should be 6524 /// passed to the target kernel as an argument. 6525 OMP_MAP_TARGET_PARAM = 0x20, 6526 /// Signal that the runtime library has to return the device pointer 6527 /// in the current position for the data being mapped. Used when we have the 6528 /// use_device_ptr clause. 6529 OMP_MAP_RETURN_PARAM = 0x40, 6530 /// This flag signals that the reference being passed is a pointer to 6531 /// private data. 6532 OMP_MAP_PRIVATE = 0x80, 6533 /// Pass the element to the device by value. 6534 OMP_MAP_LITERAL = 0x100, 6535 /// Implicit map 6536 OMP_MAP_IMPLICIT = 0x200, 6537 /// The 16 MSBs of the flags indicate whether the entry is member of some 6538 /// struct/class. 6539 OMP_MAP_MEMBER_OF = 0xffff000000000000, 6540 LLVM_MARK_AS_BITMASK_ENUM(/* LargestFlag = */ OMP_MAP_MEMBER_OF), 6541 }; 6542 6543 /// Class that associates information with a base pointer to be passed to the 6544 /// runtime library. 6545 class BasePointerInfo { 6546 /// The base pointer. 6547 llvm::Value *Ptr = nullptr; 6548 /// The base declaration that refers to this device pointer, or null if 6549 /// there is none. 6550 const ValueDecl *DevPtrDecl = nullptr; 6551 6552 public: 6553 BasePointerInfo(llvm::Value *Ptr, const ValueDecl *DevPtrDecl = nullptr) 6554 : Ptr(Ptr), DevPtrDecl(DevPtrDecl) {} 6555 llvm::Value *operator*() const { return Ptr; } 6556 const ValueDecl *getDevicePtrDecl() const { return DevPtrDecl; } 6557 void setDevicePtrDecl(const ValueDecl *D) { DevPtrDecl = D; } 6558 }; 6559 6560 using MapBaseValuesArrayTy = SmallVector<BasePointerInfo, 4>; 6561 using MapValuesArrayTy = SmallVector<llvm::Value *, 4>; 6562 using MapFlagsArrayTy = SmallVector<OpenMPOffloadMappingFlags, 4>; 6563 6564 /// Map between a struct and the its lowest & highest elements which have been 6565 /// mapped. 6566 /// [ValueDecl *] --> {LE(FieldIndex, Pointer), 6567 /// HE(FieldIndex, Pointer)} 6568 struct StructRangeInfoTy { 6569 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> LowestElem = { 6570 0, Address::invalid()}; 6571 std::pair<unsigned /*FieldIndex*/, Address /*Pointer*/> HighestElem = { 6572 0, Address::invalid()}; 6573 Address Base = Address::invalid(); 6574 }; 6575 6576 private: 6577 /// Kind that defines how a device pointer has to be returned. 6578 struct MapInfo { 6579 OMPClauseMappableExprCommon::MappableExprComponentListRef Components; 6580 OpenMPMapClauseKind MapType = OMPC_MAP_unknown; 6581 OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown; 6582 bool ReturnDevicePointer = false; 6583 bool IsImplicit = false; 6584 6585 MapInfo() = default; 6586 MapInfo( 6587 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 6588 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier, 6589 bool ReturnDevicePointer, bool IsImplicit) 6590 : Components(Components), MapType(MapType), 6591 MapTypeModifier(MapTypeModifier), 6592 ReturnDevicePointer(ReturnDevicePointer), IsImplicit(IsImplicit) {} 6593 }; 6594 6595 /// If use_device_ptr is used on a pointer which is a struct member and there 6596 /// is no map information about it, then emission of that entry is deferred 6597 /// until the whole struct has been processed. 6598 struct DeferredDevicePtrEntryTy { 6599 const Expr *IE = nullptr; 6600 const ValueDecl *VD = nullptr; 6601 6602 DeferredDevicePtrEntryTy(const Expr *IE, const ValueDecl *VD) 6603 : IE(IE), VD(VD) {} 6604 }; 6605 6606 /// Directive from where the map clauses were extracted. 6607 const OMPExecutableDirective &CurDir; 6608 6609 /// Function the directive is being generated for. 6610 CodeGenFunction &CGF; 6611 6612 /// Set of all first private variables in the current directive. 6613 llvm::SmallPtrSet<const VarDecl *, 8> FirstPrivateDecls; 6614 6615 /// Map between device pointer declarations and their expression components. 6616 /// The key value for declarations in 'this' is null. 6617 llvm::DenseMap< 6618 const ValueDecl *, 6619 SmallVector<OMPClauseMappableExprCommon::MappableExprComponentListRef, 4>> 6620 DevPointersMap; 6621 6622 llvm::Value *getExprTypeSize(const Expr *E) const { 6623 QualType ExprTy = E->getType().getCanonicalType(); 6624 6625 // Reference types are ignored for mapping purposes. 6626 if (const auto *RefTy = ExprTy->getAs<ReferenceType>()) 6627 ExprTy = RefTy->getPointeeType().getCanonicalType(); 6628 6629 // Given that an array section is considered a built-in type, we need to 6630 // do the calculation based on the length of the section instead of relying 6631 // on CGF.getTypeSize(E->getType()). 6632 if (const auto *OAE = dyn_cast<OMPArraySectionExpr>(E)) { 6633 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType( 6634 OAE->getBase()->IgnoreParenImpCasts()) 6635 .getCanonicalType(); 6636 6637 // If there is no length associated with the expression, that means we 6638 // are using the whole length of the base. 6639 if (!OAE->getLength() && OAE->getColonLoc().isValid()) 6640 return CGF.getTypeSize(BaseTy); 6641 6642 llvm::Value *ElemSize; 6643 if (const auto *PTy = BaseTy->getAs<PointerType>()) { 6644 ElemSize = CGF.getTypeSize(PTy->getPointeeType().getCanonicalType()); 6645 } else { 6646 const auto *ATy = cast<ArrayType>(BaseTy.getTypePtr()); 6647 assert(ATy && "Expecting array type if not a pointer type."); 6648 ElemSize = CGF.getTypeSize(ATy->getElementType().getCanonicalType()); 6649 } 6650 6651 // If we don't have a length at this point, that is because we have an 6652 // array section with a single element. 6653 if (!OAE->getLength()) 6654 return ElemSize; 6655 6656 llvm::Value *LengthVal = CGF.EmitScalarExpr(OAE->getLength()); 6657 LengthVal = 6658 CGF.Builder.CreateIntCast(LengthVal, CGF.SizeTy, /*isSigned=*/false); 6659 return CGF.Builder.CreateNUWMul(LengthVal, ElemSize); 6660 } 6661 return CGF.getTypeSize(ExprTy); 6662 } 6663 6664 /// Return the corresponding bits for a given map clause modifier. Add 6665 /// a flag marking the map as a pointer if requested. Add a flag marking the 6666 /// map as the first one of a series of maps that relate to the same map 6667 /// expression. 6668 OpenMPOffloadMappingFlags getMapTypeBits(OpenMPMapClauseKind MapType, 6669 OpenMPMapClauseKind MapTypeModifier, 6670 bool IsImplicit, bool AddPtrFlag, 6671 bool AddIsTargetParamFlag) const { 6672 OpenMPOffloadMappingFlags Bits = 6673 IsImplicit ? OMP_MAP_IMPLICIT : OMP_MAP_NONE; 6674 switch (MapType) { 6675 case OMPC_MAP_alloc: 6676 case OMPC_MAP_release: 6677 // alloc and release is the default behavior in the runtime library, i.e. 6678 // if we don't pass any bits alloc/release that is what the runtime is 6679 // going to do. Therefore, we don't need to signal anything for these two 6680 // type modifiers. 6681 break; 6682 case OMPC_MAP_to: 6683 Bits |= OMP_MAP_TO; 6684 break; 6685 case OMPC_MAP_from: 6686 Bits |= OMP_MAP_FROM; 6687 break; 6688 case OMPC_MAP_tofrom: 6689 Bits |= OMP_MAP_TO | OMP_MAP_FROM; 6690 break; 6691 case OMPC_MAP_delete: 6692 Bits |= OMP_MAP_DELETE; 6693 break; 6694 case OMPC_MAP_always: 6695 case OMPC_MAP_unknown: 6696 llvm_unreachable("Unexpected map type!"); 6697 } 6698 if (AddPtrFlag) 6699 Bits |= OMP_MAP_PTR_AND_OBJ; 6700 if (AddIsTargetParamFlag) 6701 Bits |= OMP_MAP_TARGET_PARAM; 6702 if (MapTypeModifier == OMPC_MAP_always) 6703 Bits |= OMP_MAP_ALWAYS; 6704 return Bits; 6705 } 6706 6707 /// Return true if the provided expression is a final array section. A 6708 /// final array section, is one whose length can't be proved to be one. 6709 bool isFinalArraySectionExpression(const Expr *E) const { 6710 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 6711 6712 // It is not an array section and therefore not a unity-size one. 6713 if (!OASE) 6714 return false; 6715 6716 // An array section with no colon always refer to a single element. 6717 if (OASE->getColonLoc().isInvalid()) 6718 return false; 6719 6720 const Expr *Length = OASE->getLength(); 6721 6722 // If we don't have a length we have to check if the array has size 1 6723 // for this dimension. Also, we should always expect a length if the 6724 // base type is pointer. 6725 if (!Length) { 6726 QualType BaseQTy = OMPArraySectionExpr::getBaseOriginalType( 6727 OASE->getBase()->IgnoreParenImpCasts()) 6728 .getCanonicalType(); 6729 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 6730 return ATy->getSize().getSExtValue() != 1; 6731 // If we don't have a constant dimension length, we have to consider 6732 // the current section as having any size, so it is not necessarily 6733 // unitary. If it happen to be unity size, that's user fault. 6734 return true; 6735 } 6736 6737 // Check if the length evaluates to 1. 6738 llvm::APSInt ConstLength; 6739 if (!Length->EvaluateAsInt(ConstLength, CGF.getContext())) 6740 return true; // Can have more that size 1. 6741 6742 return ConstLength.getSExtValue() != 1; 6743 } 6744 6745 /// Generate the base pointers, section pointers, sizes and map type 6746 /// bits for the provided map type, map modifier, and expression components. 6747 /// \a IsFirstComponent should be set to true if the provided set of 6748 /// components is the first associated with a capture. 6749 void generateInfoForComponentList( 6750 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapTypeModifier, 6751 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 6752 MapBaseValuesArrayTy &BasePointers, MapValuesArrayTy &Pointers, 6753 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types, 6754 StructRangeInfoTy &PartialStruct, bool IsFirstComponentList, 6755 bool IsImplicit) const { 6756 // The following summarizes what has to be generated for each map and the 6757 // types below. The generated information is expressed in this order: 6758 // base pointer, section pointer, size, flags 6759 // (to add to the ones that come from the map type and modifier). 6760 // 6761 // double d; 6762 // int i[100]; 6763 // float *p; 6764 // 6765 // struct S1 { 6766 // int i; 6767 // float f[50]; 6768 // } 6769 // struct S2 { 6770 // int i; 6771 // float f[50]; 6772 // S1 s; 6773 // double *p; 6774 // struct S2 *ps; 6775 // } 6776 // S2 s; 6777 // S2 *ps; 6778 // 6779 // map(d) 6780 // &d, &d, sizeof(double), TARGET_PARAM | TO | FROM 6781 // 6782 // map(i) 6783 // &i, &i, 100*sizeof(int), TARGET_PARAM | TO | FROM 6784 // 6785 // map(i[1:23]) 6786 // &i(=&i[0]), &i[1], 23*sizeof(int), TARGET_PARAM | TO | FROM 6787 // 6788 // map(p) 6789 // &p, &p, sizeof(float*), TARGET_PARAM | TO | FROM 6790 // 6791 // map(p[1:24]) 6792 // p, &p[1], 24*sizeof(float), TARGET_PARAM | TO | FROM 6793 // 6794 // map(s) 6795 // &s, &s, sizeof(S2), TARGET_PARAM | TO | FROM 6796 // 6797 // map(s.i) 6798 // &s, &(s.i), sizeof(int), TARGET_PARAM | TO | FROM 6799 // 6800 // map(s.s.f) 6801 // &s, &(s.s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM 6802 // 6803 // map(s.p) 6804 // &s, &(s.p), sizeof(double*), TARGET_PARAM | TO | FROM 6805 // 6806 // map(to: s.p[:22]) 6807 // &s, &(s.p), sizeof(double*), TARGET_PARAM (*) 6808 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) (**) 6809 // &(s.p), &(s.p[0]), 22*sizeof(double), 6810 // MEMBER_OF(1) | PTR_AND_OBJ | TO (***) 6811 // (*) alloc space for struct members, only this is a target parameter 6812 // (**) map the pointer (nothing to be mapped in this example) (the compiler 6813 // optimizes this entry out, same in the examples below) 6814 // (***) map the pointee (map: to) 6815 // 6816 // map(s.ps) 6817 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM | TO | FROM 6818 // 6819 // map(from: s.ps->s.i) 6820 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6821 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6822 // &(s.ps), &(s.ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM 6823 // 6824 // map(to: s.ps->ps) 6825 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6826 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6827 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | TO 6828 // 6829 // map(s.ps->ps->ps) 6830 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6831 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6832 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 6833 // &(s.ps->ps), &(s.ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM 6834 // 6835 // map(to: s.ps->ps->s.f[:22]) 6836 // &s, &(s.ps), sizeof(S2*), TARGET_PARAM 6837 // &s, &(s.ps), sizeof(S2*), MEMBER_OF(1) 6838 // &(s.ps), &(s.ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 6839 // &(s.ps->ps), &(s.ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO 6840 // 6841 // map(ps) 6842 // &ps, &ps, sizeof(S2*), TARGET_PARAM | TO | FROM 6843 // 6844 // map(ps->i) 6845 // ps, &(ps->i), sizeof(int), TARGET_PARAM | TO | FROM 6846 // 6847 // map(ps->s.f) 6848 // ps, &(ps->s.f[0]), 50*sizeof(float), TARGET_PARAM | TO | FROM 6849 // 6850 // map(from: ps->p) 6851 // ps, &(ps->p), sizeof(double*), TARGET_PARAM | FROM 6852 // 6853 // map(to: ps->p[:22]) 6854 // ps, &(ps->p), sizeof(double*), TARGET_PARAM 6855 // ps, &(ps->p), sizeof(double*), MEMBER_OF(1) 6856 // &(ps->p), &(ps->p[0]), 22*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | TO 6857 // 6858 // map(ps->ps) 6859 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM | TO | FROM 6860 // 6861 // map(from: ps->ps->s.i) 6862 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 6863 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 6864 // &(ps->ps), &(ps->ps->s.i), sizeof(int), MEMBER_OF(1) | PTR_AND_OBJ | FROM 6865 // 6866 // map(from: ps->ps->ps) 6867 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 6868 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 6869 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ | FROM 6870 // 6871 // map(ps->ps->ps->ps) 6872 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 6873 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 6874 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 6875 // &(ps->ps->ps), &(ps->ps->ps->ps), sizeof(S2*), PTR_AND_OBJ | TO | FROM 6876 // 6877 // map(to: ps->ps->ps->s.f[:22]) 6878 // ps, &(ps->ps), sizeof(S2*), TARGET_PARAM 6879 // ps, &(ps->ps), sizeof(S2*), MEMBER_OF(1) 6880 // &(ps->ps), &(ps->ps->ps), sizeof(S2*), MEMBER_OF(1) | PTR_AND_OBJ 6881 // &(ps->ps->ps), &(ps->ps->ps->s.f[0]), 22*sizeof(float), PTR_AND_OBJ | TO 6882 // 6883 // map(to: s.f[:22]) map(from: s.p[:33]) 6884 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1) + 6885 // sizeof(double*) (**), TARGET_PARAM 6886 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | TO 6887 // &s, &(s.p), sizeof(double*), MEMBER_OF(1) 6888 // &(s.p), &(s.p[0]), 33*sizeof(double), MEMBER_OF(1) | PTR_AND_OBJ | FROM 6889 // (*) allocate contiguous space needed to fit all mapped members even if 6890 // we allocate space for members not mapped (in this example, 6891 // s.f[22..49] and s.s are not mapped, yet we must allocate space for 6892 // them as well because they fall between &s.f[0] and &s.p) 6893 // 6894 // map(from: s.f[:22]) map(to: ps->p[:33]) 6895 // &s, &(s.f[0]), 22*sizeof(float), TARGET_PARAM | FROM 6896 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM 6897 // ps, &(ps->p), sizeof(double*), MEMBER_OF(2) (*) 6898 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(2) | PTR_AND_OBJ | TO 6899 // (*) the struct this entry pertains to is the 2nd element in the list of 6900 // arguments, hence MEMBER_OF(2) 6901 // 6902 // map(from: s.f[:22], s.s) map(to: ps->p[:33]) 6903 // &s, &(s.f[0]), 50*sizeof(float) + sizeof(struct S1), TARGET_PARAM 6904 // &s, &(s.f[0]), 22*sizeof(float), MEMBER_OF(1) | FROM 6905 // &s, &(s.s), sizeof(struct S1), MEMBER_OF(1) | FROM 6906 // ps, &(ps->p), sizeof(S2*), TARGET_PARAM 6907 // ps, &(ps->p), sizeof(double*), MEMBER_OF(4) (*) 6908 // &(ps->p), &(ps->p[0]), 33*sizeof(double), MEMBER_OF(4) | PTR_AND_OBJ | TO 6909 // (*) the struct this entry pertains to is the 4th element in the list 6910 // of arguments, hence MEMBER_OF(4) 6911 6912 // Track if the map information being generated is the first for a capture. 6913 bool IsCaptureFirstInfo = IsFirstComponentList; 6914 bool IsLink = false; // Is this variable a "declare target link"? 6915 6916 // Scan the components from the base to the complete expression. 6917 auto CI = Components.rbegin(); 6918 auto CE = Components.rend(); 6919 auto I = CI; 6920 6921 // Track if the map information being generated is the first for a list of 6922 // components. 6923 bool IsExpressionFirstInfo = true; 6924 Address BP = Address::invalid(); 6925 6926 if (isa<MemberExpr>(I->getAssociatedExpression())) { 6927 // The base is the 'this' pointer. The content of the pointer is going 6928 // to be the base of the field being mapped. 6929 BP = CGF.LoadCXXThisAddress(); 6930 } else { 6931 // The base is the reference to the variable. 6932 // BP = &Var. 6933 BP = CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress(); 6934 if (const auto *VD = 6935 dyn_cast_or_null<VarDecl>(I->getAssociatedDeclaration())) { 6936 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 6937 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 6938 if (*Res == OMPDeclareTargetDeclAttr::MT_Link) { 6939 IsLink = true; 6940 BP = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD); 6941 } 6942 } 6943 6944 // If the variable is a pointer and is being dereferenced (i.e. is not 6945 // the last component), the base has to be the pointer itself, not its 6946 // reference. References are ignored for mapping purposes. 6947 QualType Ty = 6948 I->getAssociatedDeclaration()->getType().getNonReferenceType(); 6949 if (Ty->isAnyPointerType() && std::next(I) != CE) { 6950 BP = CGF.EmitLoadOfPointer(BP, Ty->castAs<PointerType>()); 6951 6952 // We do not need to generate individual map information for the 6953 // pointer, it can be associated with the combined storage. 6954 ++I; 6955 } 6956 } 6957 6958 // Track whether a component of the list should be marked as MEMBER_OF some 6959 // combined entry (for partial structs). Only the first PTR_AND_OBJ entry 6960 // in a component list should be marked as MEMBER_OF, all subsequent entries 6961 // do not belong to the base struct. E.g. 6962 // struct S2 s; 6963 // s.ps->ps->ps->f[:] 6964 // (1) (2) (3) (4) 6965 // ps(1) is a member pointer, ps(2) is a pointee of ps(1), so it is a 6966 // PTR_AND_OBJ entry; the PTR is ps(1), so MEMBER_OF the base struct. ps(3) 6967 // is the pointee of ps(2) which is not member of struct s, so it should not 6968 // be marked as such (it is still PTR_AND_OBJ). 6969 // The variable is initialized to false so that PTR_AND_OBJ entries which 6970 // are not struct members are not considered (e.g. array of pointers to 6971 // data). 6972 bool ShouldBeMemberOf = false; 6973 6974 // Variable keeping track of whether or not we have encountered a component 6975 // in the component list which is a member expression. Useful when we have a 6976 // pointer or a final array section, in which case it is the previous 6977 // component in the list which tells us whether we have a member expression. 6978 // E.g. X.f[:] 6979 // While processing the final array section "[:]" it is "f" which tells us 6980 // whether we are dealing with a member of a declared struct. 6981 const MemberExpr *EncounteredME = nullptr; 6982 6983 for (; I != CE; ++I) { 6984 // If the current component is member of a struct (parent struct) mark it. 6985 if (!EncounteredME) { 6986 EncounteredME = dyn_cast<MemberExpr>(I->getAssociatedExpression()); 6987 // If we encounter a PTR_AND_OBJ entry from now on it should be marked 6988 // as MEMBER_OF the parent struct. 6989 if (EncounteredME) 6990 ShouldBeMemberOf = true; 6991 } 6992 6993 auto Next = std::next(I); 6994 6995 // We need to generate the addresses and sizes if this is the last 6996 // component, if the component is a pointer or if it is an array section 6997 // whose length can't be proved to be one. If this is a pointer, it 6998 // becomes the base address for the following components. 6999 7000 // A final array section, is one whose length can't be proved to be one. 7001 bool IsFinalArraySection = 7002 isFinalArraySectionExpression(I->getAssociatedExpression()); 7003 7004 // Get information on whether the element is a pointer. Have to do a 7005 // special treatment for array sections given that they are built-in 7006 // types. 7007 const auto *OASE = 7008 dyn_cast<OMPArraySectionExpr>(I->getAssociatedExpression()); 7009 bool IsPointer = 7010 (OASE && OMPArraySectionExpr::getBaseOriginalType(OASE) 7011 .getCanonicalType() 7012 ->isAnyPointerType()) || 7013 I->getAssociatedExpression()->getType()->isAnyPointerType(); 7014 7015 if (Next == CE || IsPointer || IsFinalArraySection) { 7016 // If this is not the last component, we expect the pointer to be 7017 // associated with an array expression or member expression. 7018 assert((Next == CE || 7019 isa<MemberExpr>(Next->getAssociatedExpression()) || 7020 isa<ArraySubscriptExpr>(Next->getAssociatedExpression()) || 7021 isa<OMPArraySectionExpr>(Next->getAssociatedExpression())) && 7022 "Unexpected expression"); 7023 7024 Address LB = 7025 CGF.EmitOMPSharedLValue(I->getAssociatedExpression()).getAddress(); 7026 llvm::Value *Size = getExprTypeSize(I->getAssociatedExpression()); 7027 7028 // If this component is a pointer inside the base struct then we don't 7029 // need to create any entry for it - it will be combined with the object 7030 // it is pointing to into a single PTR_AND_OBJ entry. 7031 bool IsMemberPointer = 7032 IsPointer && EncounteredME && 7033 (dyn_cast<MemberExpr>(I->getAssociatedExpression()) == 7034 EncounteredME); 7035 if (!IsMemberPointer) { 7036 BasePointers.push_back(BP.getPointer()); 7037 Pointers.push_back(LB.getPointer()); 7038 Sizes.push_back(Size); 7039 7040 // We need to add a pointer flag for each map that comes from the 7041 // same expression except for the first one. We also need to signal 7042 // this map is the first one that relates with the current capture 7043 // (there is a set of entries for each capture). 7044 OpenMPOffloadMappingFlags Flags = getMapTypeBits( 7045 MapType, MapTypeModifier, IsImplicit, 7046 !IsExpressionFirstInfo || IsLink, IsCaptureFirstInfo && !IsLink); 7047 7048 if (!IsExpressionFirstInfo) { 7049 // If we have a PTR_AND_OBJ pair where the OBJ is a pointer as well, 7050 // then we reset the TO/FROM/ALWAYS/DELETE flags. 7051 if (IsPointer) 7052 Flags &= ~(OMP_MAP_TO | OMP_MAP_FROM | OMP_MAP_ALWAYS | 7053 OMP_MAP_DELETE); 7054 7055 if (ShouldBeMemberOf) { 7056 // Set placeholder value MEMBER_OF=FFFF to indicate that the flag 7057 // should be later updated with the correct value of MEMBER_OF. 7058 Flags |= OMP_MAP_MEMBER_OF; 7059 // From now on, all subsequent PTR_AND_OBJ entries should not be 7060 // marked as MEMBER_OF. 7061 ShouldBeMemberOf = false; 7062 } 7063 } 7064 7065 Types.push_back(Flags); 7066 } 7067 7068 // If we have encountered a member expression so far, keep track of the 7069 // mapped member. If the parent is "*this", then the value declaration 7070 // is nullptr. 7071 if (EncounteredME) { 7072 const auto *FD = dyn_cast<FieldDecl>(EncounteredME->getMemberDecl()); 7073 unsigned FieldIndex = FD->getFieldIndex(); 7074 7075 // Update info about the lowest and highest elements for this struct 7076 if (!PartialStruct.Base.isValid()) { 7077 PartialStruct.LowestElem = {FieldIndex, LB}; 7078 PartialStruct.HighestElem = {FieldIndex, LB}; 7079 PartialStruct.Base = BP; 7080 } else if (FieldIndex < PartialStruct.LowestElem.first) { 7081 PartialStruct.LowestElem = {FieldIndex, LB}; 7082 } else if (FieldIndex > PartialStruct.HighestElem.first) { 7083 PartialStruct.HighestElem = {FieldIndex, LB}; 7084 } 7085 } 7086 7087 // If we have a final array section, we are done with this expression. 7088 if (IsFinalArraySection) 7089 break; 7090 7091 // The pointer becomes the base for the next element. 7092 if (Next != CE) 7093 BP = LB; 7094 7095 IsExpressionFirstInfo = false; 7096 IsCaptureFirstInfo = false; 7097 } 7098 } 7099 } 7100 7101 /// Return the adjusted map modifiers if the declaration a capture refers to 7102 /// appears in a first-private clause. This is expected to be used only with 7103 /// directives that start with 'target'. 7104 MappableExprsHandler::OpenMPOffloadMappingFlags 7105 getMapModifiersForPrivateClauses(const CapturedStmt::Capture &Cap) const { 7106 assert(Cap.capturesVariable() && "Expected capture by reference only!"); 7107 7108 // A first private variable captured by reference will use only the 7109 // 'private ptr' and 'map to' flag. Return the right flags if the captured 7110 // declaration is known as first-private in this handler. 7111 if (FirstPrivateDecls.count(Cap.getCapturedVar())) 7112 return MappableExprsHandler::OMP_MAP_PRIVATE | 7113 MappableExprsHandler::OMP_MAP_TO; 7114 return MappableExprsHandler::OMP_MAP_TO | 7115 MappableExprsHandler::OMP_MAP_FROM; 7116 } 7117 7118 static OpenMPOffloadMappingFlags getMemberOfFlag(unsigned Position) { 7119 // Member of is given by the 16 MSB of the flag, so rotate by 48 bits. 7120 return static_cast<OpenMPOffloadMappingFlags>(((uint64_t)Position + 1) 7121 << 48); 7122 } 7123 7124 static void setCorrectMemberOfFlag(OpenMPOffloadMappingFlags &Flags, 7125 OpenMPOffloadMappingFlags MemberOfFlag) { 7126 // If the entry is PTR_AND_OBJ but has not been marked with the special 7127 // placeholder value 0xFFFF in the MEMBER_OF field, then it should not be 7128 // marked as MEMBER_OF. 7129 if ((Flags & OMP_MAP_PTR_AND_OBJ) && 7130 ((Flags & OMP_MAP_MEMBER_OF) != OMP_MAP_MEMBER_OF)) 7131 return; 7132 7133 // Reset the placeholder value to prepare the flag for the assignment of the 7134 // proper MEMBER_OF value. 7135 Flags &= ~OMP_MAP_MEMBER_OF; 7136 Flags |= MemberOfFlag; 7137 } 7138 7139 public: 7140 MappableExprsHandler(const OMPExecutableDirective &Dir, CodeGenFunction &CGF) 7141 : CurDir(Dir), CGF(CGF) { 7142 // Extract firstprivate clause information. 7143 for (const auto *C : Dir.getClausesOfKind<OMPFirstprivateClause>()) 7144 for (const auto *D : C->varlists()) 7145 FirstPrivateDecls.insert( 7146 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl()); 7147 // Extract device pointer clause information. 7148 for (const auto *C : Dir.getClausesOfKind<OMPIsDevicePtrClause>()) 7149 for (auto L : C->component_lists()) 7150 DevPointersMap[L.first].push_back(L.second); 7151 } 7152 7153 /// Generate code for the combined entry if we have a partially mapped struct 7154 /// and take care of the mapping flags of the arguments corresponding to 7155 /// individual struct members. 7156 void emitCombinedEntry(MapBaseValuesArrayTy &BasePointers, 7157 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes, 7158 MapFlagsArrayTy &Types, MapFlagsArrayTy &CurTypes, 7159 const StructRangeInfoTy &PartialStruct) const { 7160 // Base is the base of the struct 7161 BasePointers.push_back(PartialStruct.Base.getPointer()); 7162 // Pointer is the address of the lowest element 7163 llvm::Value *LB = PartialStruct.LowestElem.second.getPointer(); 7164 Pointers.push_back(LB); 7165 // Size is (addr of {highest+1} element) - (addr of lowest element) 7166 llvm::Value *HB = PartialStruct.HighestElem.second.getPointer(); 7167 llvm::Value *HAddr = CGF.Builder.CreateConstGEP1_32(HB, /*Idx0=*/1); 7168 llvm::Value *CLAddr = CGF.Builder.CreatePointerCast(LB, CGF.VoidPtrTy); 7169 llvm::Value *CHAddr = CGF.Builder.CreatePointerCast(HAddr, CGF.VoidPtrTy); 7170 llvm::Value *Diff = CGF.Builder.CreatePtrDiff(CHAddr, CLAddr); 7171 llvm::Value *Size = CGF.Builder.CreateIntCast(Diff, CGF.SizeTy, 7172 /*isSinged=*/false); 7173 Sizes.push_back(Size); 7174 // Map type is always TARGET_PARAM 7175 Types.push_back(OMP_MAP_TARGET_PARAM); 7176 // Remove TARGET_PARAM flag from the first element 7177 (*CurTypes.begin()) &= ~OMP_MAP_TARGET_PARAM; 7178 7179 // All other current entries will be MEMBER_OF the combined entry 7180 // (except for PTR_AND_OBJ entries which do not have a placeholder value 7181 // 0xFFFF in the MEMBER_OF field). 7182 OpenMPOffloadMappingFlags MemberOfFlag = 7183 getMemberOfFlag(BasePointers.size() - 1); 7184 for (auto &M : CurTypes) 7185 setCorrectMemberOfFlag(M, MemberOfFlag); 7186 } 7187 7188 /// Generate all the base pointers, section pointers, sizes and map 7189 /// types for the extracted mappable expressions. Also, for each item that 7190 /// relates with a device pointer, a pair of the relevant declaration and 7191 /// index where it occurs is appended to the device pointers info array. 7192 void generateAllInfo(MapBaseValuesArrayTy &BasePointers, 7193 MapValuesArrayTy &Pointers, MapValuesArrayTy &Sizes, 7194 MapFlagsArrayTy &Types) const { 7195 // We have to process the component lists that relate with the same 7196 // declaration in a single chunk so that we can generate the map flags 7197 // correctly. Therefore, we organize all lists in a map. 7198 llvm::MapVector<const ValueDecl *, SmallVector<MapInfo, 8>> Info; 7199 7200 // Helper function to fill the information map for the different supported 7201 // clauses. 7202 auto &&InfoGen = [&Info]( 7203 const ValueDecl *D, 7204 OMPClauseMappableExprCommon::MappableExprComponentListRef L, 7205 OpenMPMapClauseKind MapType, OpenMPMapClauseKind MapModifier, 7206 bool ReturnDevicePointer, bool IsImplicit) { 7207 const ValueDecl *VD = 7208 D ? cast<ValueDecl>(D->getCanonicalDecl()) : nullptr; 7209 Info[VD].emplace_back(L, MapType, MapModifier, ReturnDevicePointer, 7210 IsImplicit); 7211 }; 7212 7213 // FIXME: MSVC 2013 seems to require this-> to find member CurDir. 7214 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) 7215 for (const auto &L : C->component_lists()) { 7216 InfoGen(L.first, L.second, C->getMapType(), C->getMapTypeModifier(), 7217 /*ReturnDevicePointer=*/false, C->isImplicit()); 7218 } 7219 for (const auto *C : this->CurDir.getClausesOfKind<OMPToClause>()) 7220 for (const auto &L : C->component_lists()) { 7221 InfoGen(L.first, L.second, OMPC_MAP_to, OMPC_MAP_unknown, 7222 /*ReturnDevicePointer=*/false, C->isImplicit()); 7223 } 7224 for (const auto *C : this->CurDir.getClausesOfKind<OMPFromClause>()) 7225 for (const auto &L : C->component_lists()) { 7226 InfoGen(L.first, L.second, OMPC_MAP_from, OMPC_MAP_unknown, 7227 /*ReturnDevicePointer=*/false, C->isImplicit()); 7228 } 7229 7230 // Look at the use_device_ptr clause information and mark the existing map 7231 // entries as such. If there is no map information for an entry in the 7232 // use_device_ptr list, we create one with map type 'alloc' and zero size 7233 // section. It is the user fault if that was not mapped before. If there is 7234 // no map information and the pointer is a struct member, then we defer the 7235 // emission of that entry until the whole struct has been processed. 7236 llvm::MapVector<const ValueDecl *, SmallVector<DeferredDevicePtrEntryTy, 4>> 7237 DeferredInfo; 7238 7239 // FIXME: MSVC 2013 seems to require this-> to find member CurDir. 7240 for (const auto *C : 7241 this->CurDir.getClausesOfKind<OMPUseDevicePtrClause>()) { 7242 for (const auto &L : C->component_lists()) { 7243 assert(!L.second.empty() && "Not expecting empty list of components!"); 7244 const ValueDecl *VD = L.second.back().getAssociatedDeclaration(); 7245 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 7246 const Expr *IE = L.second.back().getAssociatedExpression(); 7247 // If the first component is a member expression, we have to look into 7248 // 'this', which maps to null in the map of map information. Otherwise 7249 // look directly for the information. 7250 auto It = Info.find(isa<MemberExpr>(IE) ? nullptr : VD); 7251 7252 // We potentially have map information for this declaration already. 7253 // Look for the first set of components that refer to it. 7254 if (It != Info.end()) { 7255 auto CI = std::find_if( 7256 It->second.begin(), It->second.end(), [VD](const MapInfo &MI) { 7257 return MI.Components.back().getAssociatedDeclaration() == VD; 7258 }); 7259 // If we found a map entry, signal that the pointer has to be returned 7260 // and move on to the next declaration. 7261 if (CI != It->second.end()) { 7262 CI->ReturnDevicePointer = true; 7263 continue; 7264 } 7265 } 7266 7267 // We didn't find any match in our map information - generate a zero 7268 // size array section - if the pointer is a struct member we defer this 7269 // action until the whole struct has been processed. 7270 // FIXME: MSVC 2013 seems to require this-> to find member CGF. 7271 if (isa<MemberExpr>(IE)) { 7272 // Insert the pointer into Info to be processed by 7273 // generateInfoForComponentList. Because it is a member pointer 7274 // without a pointee, no entry will be generated for it, therefore 7275 // we need to generate one after the whole struct has been processed. 7276 // Nonetheless, generateInfoForComponentList must be called to take 7277 // the pointer into account for the calculation of the range of the 7278 // partial struct. 7279 InfoGen(nullptr, L.second, OMPC_MAP_unknown, OMPC_MAP_unknown, 7280 /*ReturnDevicePointer=*/false, C->isImplicit()); 7281 DeferredInfo[nullptr].emplace_back(IE, VD); 7282 } else { 7283 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar( 7284 this->CGF.EmitLValue(IE), IE->getExprLoc()); 7285 BasePointers.emplace_back(Ptr, VD); 7286 Pointers.push_back(Ptr); 7287 Sizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy)); 7288 Types.push_back(OMP_MAP_RETURN_PARAM | OMP_MAP_TARGET_PARAM); 7289 } 7290 } 7291 } 7292 7293 for (const auto &M : Info) { 7294 // We need to know when we generate information for the first component 7295 // associated with a capture, because the mapping flags depend on it. 7296 bool IsFirstComponentList = true; 7297 7298 // Temporary versions of arrays 7299 MapBaseValuesArrayTy CurBasePointers; 7300 MapValuesArrayTy CurPointers; 7301 MapValuesArrayTy CurSizes; 7302 MapFlagsArrayTy CurTypes; 7303 StructRangeInfoTy PartialStruct; 7304 7305 for (const MapInfo &L : M.second) { 7306 assert(!L.Components.empty() && 7307 "Not expecting declaration with no component lists."); 7308 7309 // Remember the current base pointer index. 7310 unsigned CurrentBasePointersIdx = CurBasePointers.size(); 7311 // FIXME: MSVC 2013 seems to require this-> to find the member method. 7312 this->generateInfoForComponentList( 7313 L.MapType, L.MapTypeModifier, L.Components, CurBasePointers, 7314 CurPointers, CurSizes, CurTypes, PartialStruct, 7315 IsFirstComponentList, L.IsImplicit); 7316 7317 // If this entry relates with a device pointer, set the relevant 7318 // declaration and add the 'return pointer' flag. 7319 if (L.ReturnDevicePointer) { 7320 assert(CurBasePointers.size() > CurrentBasePointersIdx && 7321 "Unexpected number of mapped base pointers."); 7322 7323 const ValueDecl *RelevantVD = 7324 L.Components.back().getAssociatedDeclaration(); 7325 assert(RelevantVD && 7326 "No relevant declaration related with device pointer??"); 7327 7328 CurBasePointers[CurrentBasePointersIdx].setDevicePtrDecl(RelevantVD); 7329 CurTypes[CurrentBasePointersIdx] |= OMP_MAP_RETURN_PARAM; 7330 } 7331 IsFirstComponentList = false; 7332 } 7333 7334 // Append any pending zero-length pointers which are struct members and 7335 // used with use_device_ptr. 7336 auto CI = DeferredInfo.find(M.first); 7337 if (CI != DeferredInfo.end()) { 7338 for (const DeferredDevicePtrEntryTy &L : CI->second) { 7339 llvm::Value *BasePtr = this->CGF.EmitLValue(L.IE).getPointer(); 7340 llvm::Value *Ptr = this->CGF.EmitLoadOfScalar( 7341 this->CGF.EmitLValue(L.IE), L.IE->getExprLoc()); 7342 CurBasePointers.emplace_back(BasePtr, L.VD); 7343 CurPointers.push_back(Ptr); 7344 CurSizes.push_back(llvm::Constant::getNullValue(this->CGF.SizeTy)); 7345 // Entry is PTR_AND_OBJ and RETURN_PARAM. Also, set the placeholder 7346 // value MEMBER_OF=FFFF so that the entry is later updated with the 7347 // correct value of MEMBER_OF. 7348 CurTypes.push_back(OMP_MAP_PTR_AND_OBJ | OMP_MAP_RETURN_PARAM | 7349 OMP_MAP_MEMBER_OF); 7350 } 7351 } 7352 7353 // If there is an entry in PartialStruct it means we have a struct with 7354 // individual members mapped. Emit an extra combined entry. 7355 if (PartialStruct.Base.isValid()) 7356 emitCombinedEntry(BasePointers, Pointers, Sizes, Types, CurTypes, 7357 PartialStruct); 7358 7359 // We need to append the results of this capture to what we already have. 7360 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end()); 7361 Pointers.append(CurPointers.begin(), CurPointers.end()); 7362 Sizes.append(CurSizes.begin(), CurSizes.end()); 7363 Types.append(CurTypes.begin(), CurTypes.end()); 7364 } 7365 } 7366 7367 /// Generate the base pointers, section pointers, sizes and map types 7368 /// associated to a given capture. 7369 void generateInfoForCapture(const CapturedStmt::Capture *Cap, 7370 llvm::Value *Arg, 7371 MapBaseValuesArrayTy &BasePointers, 7372 MapValuesArrayTy &Pointers, 7373 MapValuesArrayTy &Sizes, MapFlagsArrayTy &Types, 7374 StructRangeInfoTy &PartialStruct) const { 7375 assert(!Cap->capturesVariableArrayType() && 7376 "Not expecting to generate map info for a variable array type!"); 7377 7378 // We need to know when we generating information for the first component 7379 // associated with a capture, because the mapping flags depend on it. 7380 bool IsFirstComponentList = true; 7381 7382 const ValueDecl *VD = Cap->capturesThis() 7383 ? nullptr 7384 : Cap->getCapturedVar()->getCanonicalDecl(); 7385 7386 // If this declaration appears in a is_device_ptr clause we just have to 7387 // pass the pointer by value. If it is a reference to a declaration, we just 7388 // pass its value. 7389 if (DevPointersMap.count(VD)) { 7390 BasePointers.emplace_back(Arg, VD); 7391 Pointers.push_back(Arg); 7392 Sizes.push_back(CGF.getTypeSize(CGF.getContext().VoidPtrTy)); 7393 Types.push_back(OMP_MAP_LITERAL | OMP_MAP_TARGET_PARAM); 7394 return; 7395 } 7396 7397 // FIXME: MSVC 2013 seems to require this-> to find member CurDir. 7398 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) 7399 for (const auto &L : C->decl_component_lists(VD)) { 7400 assert(L.first == VD && 7401 "We got information for the wrong declaration??"); 7402 assert(!L.second.empty() && 7403 "Not expecting declaration with no component lists."); 7404 generateInfoForComponentList(C->getMapType(), C->getMapTypeModifier(), 7405 L.second, BasePointers, Pointers, Sizes, 7406 Types, PartialStruct, IsFirstComponentList, 7407 C->isImplicit()); 7408 IsFirstComponentList = false; 7409 } 7410 } 7411 7412 /// Generate the base pointers, section pointers, sizes and map types 7413 /// associated with the declare target link variables. 7414 void generateInfoForDeclareTargetLink(MapBaseValuesArrayTy &BasePointers, 7415 MapValuesArrayTy &Pointers, 7416 MapValuesArrayTy &Sizes, 7417 MapFlagsArrayTy &Types) const { 7418 // Map other list items in the map clause which are not captured variables 7419 // but "declare target link" global variables., 7420 for (const auto *C : this->CurDir.getClausesOfKind<OMPMapClause>()) { 7421 for (const auto &L : C->component_lists()) { 7422 if (!L.first) 7423 continue; 7424 const auto *VD = dyn_cast<VarDecl>(L.first); 7425 if (!VD) 7426 continue; 7427 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 7428 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 7429 if (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) 7430 continue; 7431 StructRangeInfoTy PartialStruct; 7432 generateInfoForComponentList( 7433 C->getMapType(), C->getMapTypeModifier(), L.second, BasePointers, 7434 Pointers, Sizes, Types, PartialStruct, 7435 /*IsFirstComponentList=*/true, C->isImplicit()); 7436 assert(!PartialStruct.Base.isValid() && 7437 "No partial structs for declare target link expected."); 7438 } 7439 } 7440 } 7441 7442 /// Generate the default map information for a given capture \a CI, 7443 /// record field declaration \a RI and captured value \a CV. 7444 void generateDefaultMapInfo(const CapturedStmt::Capture &CI, 7445 const FieldDecl &RI, llvm::Value *CV, 7446 MapBaseValuesArrayTy &CurBasePointers, 7447 MapValuesArrayTy &CurPointers, 7448 MapValuesArrayTy &CurSizes, 7449 MapFlagsArrayTy &CurMapTypes) const { 7450 // Do the default mapping. 7451 if (CI.capturesThis()) { 7452 CurBasePointers.push_back(CV); 7453 CurPointers.push_back(CV); 7454 const auto *PtrTy = cast<PointerType>(RI.getType().getTypePtr()); 7455 CurSizes.push_back(CGF.getTypeSize(PtrTy->getPointeeType())); 7456 // Default map type. 7457 CurMapTypes.push_back(OMP_MAP_TO | OMP_MAP_FROM); 7458 } else if (CI.capturesVariableByCopy()) { 7459 CurBasePointers.push_back(CV); 7460 CurPointers.push_back(CV); 7461 if (!RI.getType()->isAnyPointerType()) { 7462 // We have to signal to the runtime captures passed by value that are 7463 // not pointers. 7464 CurMapTypes.push_back(OMP_MAP_LITERAL); 7465 CurSizes.push_back(CGF.getTypeSize(RI.getType())); 7466 } else { 7467 // Pointers are implicitly mapped with a zero size and no flags 7468 // (other than first map that is added for all implicit maps). 7469 CurMapTypes.push_back(OMP_MAP_NONE); 7470 CurSizes.push_back(llvm::Constant::getNullValue(CGF.SizeTy)); 7471 } 7472 } else { 7473 assert(CI.capturesVariable() && "Expected captured reference."); 7474 CurBasePointers.push_back(CV); 7475 CurPointers.push_back(CV); 7476 7477 const auto *PtrTy = cast<ReferenceType>(RI.getType().getTypePtr()); 7478 QualType ElementType = PtrTy->getPointeeType(); 7479 CurSizes.push_back(CGF.getTypeSize(ElementType)); 7480 // The default map type for a scalar/complex type is 'to' because by 7481 // default the value doesn't have to be retrieved. For an aggregate 7482 // type, the default is 'tofrom'. 7483 CurMapTypes.push_back(getMapModifiersForPrivateClauses(CI)); 7484 } 7485 // Every default map produces a single argument which is a target parameter. 7486 CurMapTypes.back() |= OMP_MAP_TARGET_PARAM; 7487 7488 // Add flag stating this is an implicit map. 7489 CurMapTypes.back() |= OMP_MAP_IMPLICIT; 7490 } 7491 }; 7492 7493 enum OpenMPOffloadingReservedDeviceIDs { 7494 /// Device ID if the device was not defined, runtime should get it 7495 /// from environment variables in the spec. 7496 OMP_DEVICEID_UNDEF = -1, 7497 }; 7498 } // anonymous namespace 7499 7500 /// Emit the arrays used to pass the captures and map information to the 7501 /// offloading runtime library. If there is no map or capture information, 7502 /// return nullptr by reference. 7503 static void 7504 emitOffloadingArrays(CodeGenFunction &CGF, 7505 MappableExprsHandler::MapBaseValuesArrayTy &BasePointers, 7506 MappableExprsHandler::MapValuesArrayTy &Pointers, 7507 MappableExprsHandler::MapValuesArrayTy &Sizes, 7508 MappableExprsHandler::MapFlagsArrayTy &MapTypes, 7509 CGOpenMPRuntime::TargetDataInfo &Info) { 7510 CodeGenModule &CGM = CGF.CGM; 7511 ASTContext &Ctx = CGF.getContext(); 7512 7513 // Reset the array information. 7514 Info.clearArrayInfo(); 7515 Info.NumberOfPtrs = BasePointers.size(); 7516 7517 if (Info.NumberOfPtrs) { 7518 // Detect if we have any capture size requiring runtime evaluation of the 7519 // size so that a constant array could be eventually used. 7520 bool hasRuntimeEvaluationCaptureSize = false; 7521 for (llvm::Value *S : Sizes) 7522 if (!isa<llvm::Constant>(S)) { 7523 hasRuntimeEvaluationCaptureSize = true; 7524 break; 7525 } 7526 7527 llvm::APInt PointerNumAP(32, Info.NumberOfPtrs, /*isSigned=*/true); 7528 QualType PointerArrayType = 7529 Ctx.getConstantArrayType(Ctx.VoidPtrTy, PointerNumAP, ArrayType::Normal, 7530 /*IndexTypeQuals=*/0); 7531 7532 Info.BasePointersArray = 7533 CGF.CreateMemTemp(PointerArrayType, ".offload_baseptrs").getPointer(); 7534 Info.PointersArray = 7535 CGF.CreateMemTemp(PointerArrayType, ".offload_ptrs").getPointer(); 7536 7537 // If we don't have any VLA types or other types that require runtime 7538 // evaluation, we can use a constant array for the map sizes, otherwise we 7539 // need to fill up the arrays as we do for the pointers. 7540 if (hasRuntimeEvaluationCaptureSize) { 7541 QualType SizeArrayType = Ctx.getConstantArrayType( 7542 Ctx.getSizeType(), PointerNumAP, ArrayType::Normal, 7543 /*IndexTypeQuals=*/0); 7544 Info.SizesArray = 7545 CGF.CreateMemTemp(SizeArrayType, ".offload_sizes").getPointer(); 7546 } else { 7547 // We expect all the sizes to be constant, so we collect them to create 7548 // a constant array. 7549 SmallVector<llvm::Constant *, 16> ConstSizes; 7550 for (llvm::Value *S : Sizes) 7551 ConstSizes.push_back(cast<llvm::Constant>(S)); 7552 7553 auto *SizesArrayInit = llvm::ConstantArray::get( 7554 llvm::ArrayType::get(CGM.SizeTy, ConstSizes.size()), ConstSizes); 7555 std::string Name = CGM.getOpenMPRuntime().getName({"offload_sizes"}); 7556 auto *SizesArrayGbl = new llvm::GlobalVariable( 7557 CGM.getModule(), SizesArrayInit->getType(), 7558 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, 7559 SizesArrayInit, Name); 7560 SizesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 7561 Info.SizesArray = SizesArrayGbl; 7562 } 7563 7564 // The map types are always constant so we don't need to generate code to 7565 // fill arrays. Instead, we create an array constant. 7566 SmallVector<uint64_t, 4> Mapping(MapTypes.size(), 0); 7567 llvm::copy(MapTypes, Mapping.begin()); 7568 llvm::Constant *MapTypesArrayInit = 7569 llvm::ConstantDataArray::get(CGF.Builder.getContext(), Mapping); 7570 std::string MaptypesName = 7571 CGM.getOpenMPRuntime().getName({"offload_maptypes"}); 7572 auto *MapTypesArrayGbl = new llvm::GlobalVariable( 7573 CGM.getModule(), MapTypesArrayInit->getType(), 7574 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, 7575 MapTypesArrayInit, MaptypesName); 7576 MapTypesArrayGbl->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 7577 Info.MapTypesArray = MapTypesArrayGbl; 7578 7579 for (unsigned I = 0; I < Info.NumberOfPtrs; ++I) { 7580 llvm::Value *BPVal = *BasePointers[I]; 7581 llvm::Value *BP = CGF.Builder.CreateConstInBoundsGEP2_32( 7582 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 7583 Info.BasePointersArray, 0, I); 7584 BP = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 7585 BP, BPVal->getType()->getPointerTo(/*AddrSpace=*/0)); 7586 Address BPAddr(BP, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy)); 7587 CGF.Builder.CreateStore(BPVal, BPAddr); 7588 7589 if (Info.requiresDevicePointerInfo()) 7590 if (const ValueDecl *DevVD = BasePointers[I].getDevicePtrDecl()) 7591 Info.CaptureDeviceAddrMap.try_emplace(DevVD, BPAddr); 7592 7593 llvm::Value *PVal = Pointers[I]; 7594 llvm::Value *P = CGF.Builder.CreateConstInBoundsGEP2_32( 7595 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 7596 Info.PointersArray, 0, I); 7597 P = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 7598 P, PVal->getType()->getPointerTo(/*AddrSpace=*/0)); 7599 Address PAddr(P, Ctx.getTypeAlignInChars(Ctx.VoidPtrTy)); 7600 CGF.Builder.CreateStore(PVal, PAddr); 7601 7602 if (hasRuntimeEvaluationCaptureSize) { 7603 llvm::Value *S = CGF.Builder.CreateConstInBoundsGEP2_32( 7604 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), 7605 Info.SizesArray, 7606 /*Idx0=*/0, 7607 /*Idx1=*/I); 7608 Address SAddr(S, Ctx.getTypeAlignInChars(Ctx.getSizeType())); 7609 CGF.Builder.CreateStore( 7610 CGF.Builder.CreateIntCast(Sizes[I], CGM.SizeTy, /*isSigned=*/true), 7611 SAddr); 7612 } 7613 } 7614 } 7615 } 7616 /// Emit the arguments to be passed to the runtime library based on the 7617 /// arrays of pointers, sizes and map types. 7618 static void emitOffloadingArraysArgument( 7619 CodeGenFunction &CGF, llvm::Value *&BasePointersArrayArg, 7620 llvm::Value *&PointersArrayArg, llvm::Value *&SizesArrayArg, 7621 llvm::Value *&MapTypesArrayArg, CGOpenMPRuntime::TargetDataInfo &Info) { 7622 CodeGenModule &CGM = CGF.CGM; 7623 if (Info.NumberOfPtrs) { 7624 BasePointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 7625 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 7626 Info.BasePointersArray, 7627 /*Idx0=*/0, /*Idx1=*/0); 7628 PointersArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 7629 llvm::ArrayType::get(CGM.VoidPtrTy, Info.NumberOfPtrs), 7630 Info.PointersArray, 7631 /*Idx0=*/0, 7632 /*Idx1=*/0); 7633 SizesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 7634 llvm::ArrayType::get(CGM.SizeTy, Info.NumberOfPtrs), Info.SizesArray, 7635 /*Idx0=*/0, /*Idx1=*/0); 7636 MapTypesArrayArg = CGF.Builder.CreateConstInBoundsGEP2_32( 7637 llvm::ArrayType::get(CGM.Int64Ty, Info.NumberOfPtrs), 7638 Info.MapTypesArray, 7639 /*Idx0=*/0, 7640 /*Idx1=*/0); 7641 } else { 7642 BasePointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy); 7643 PointersArrayArg = llvm::ConstantPointerNull::get(CGM.VoidPtrPtrTy); 7644 SizesArrayArg = llvm::ConstantPointerNull::get(CGM.SizeTy->getPointerTo()); 7645 MapTypesArrayArg = 7646 llvm::ConstantPointerNull::get(CGM.Int64Ty->getPointerTo()); 7647 } 7648 } 7649 7650 void CGOpenMPRuntime::emitTargetCall(CodeGenFunction &CGF, 7651 const OMPExecutableDirective &D, 7652 llvm::Value *OutlinedFn, 7653 llvm::Value *OutlinedFnID, 7654 const Expr *IfCond, const Expr *Device) { 7655 if (!CGF.HaveInsertPoint()) 7656 return; 7657 7658 assert(OutlinedFn && "Invalid outlined function!"); 7659 7660 const bool RequiresOuterTask = D.hasClausesOfKind<OMPDependClause>(); 7661 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 7662 const CapturedStmt &CS = *D.getCapturedStmt(OMPD_target); 7663 auto &&ArgsCodegen = [&CS, &CapturedVars](CodeGenFunction &CGF, 7664 PrePostActionTy &) { 7665 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars); 7666 }; 7667 emitInlinedDirective(CGF, OMPD_unknown, ArgsCodegen); 7668 7669 CodeGenFunction::OMPTargetDataInfo InputInfo; 7670 llvm::Value *MapTypesArray = nullptr; 7671 // Fill up the pointer arrays and transfer execution to the device. 7672 auto &&ThenGen = [this, Device, OutlinedFn, OutlinedFnID, &D, &InputInfo, 7673 &MapTypesArray, &CS, RequiresOuterTask, 7674 &CapturedVars](CodeGenFunction &CGF, PrePostActionTy &) { 7675 // On top of the arrays that were filled up, the target offloading call 7676 // takes as arguments the device id as well as the host pointer. The host 7677 // pointer is used by the runtime library to identify the current target 7678 // region, so it only has to be unique and not necessarily point to 7679 // anything. It could be the pointer to the outlined function that 7680 // implements the target region, but we aren't using that so that the 7681 // compiler doesn't need to keep that, and could therefore inline the host 7682 // function if proven worthwhile during optimization. 7683 7684 // From this point on, we need to have an ID of the target region defined. 7685 assert(OutlinedFnID && "Invalid outlined function ID!"); 7686 7687 // Emit device ID if any. 7688 llvm::Value *DeviceID; 7689 if (Device) { 7690 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 7691 CGF.Int64Ty, /*isSigned=*/true); 7692 } else { 7693 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 7694 } 7695 7696 // Emit the number of elements in the offloading arrays. 7697 llvm::Value *PointerNum = 7698 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems); 7699 7700 // Return value of the runtime offloading call. 7701 llvm::Value *Return; 7702 7703 llvm::Value *NumTeams = emitNumTeamsForTargetDirective(*this, CGF, D); 7704 llvm::Value *NumThreads = emitNumThreadsForTargetDirective(*this, CGF, D); 7705 7706 bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>(); 7707 // The target region is an outlined function launched by the runtime 7708 // via calls __tgt_target() or __tgt_target_teams(). 7709 // 7710 // __tgt_target() launches a target region with one team and one thread, 7711 // executing a serial region. This master thread may in turn launch 7712 // more threads within its team upon encountering a parallel region, 7713 // however, no additional teams can be launched on the device. 7714 // 7715 // __tgt_target_teams() launches a target region with one or more teams, 7716 // each with one or more threads. This call is required for target 7717 // constructs such as: 7718 // 'target teams' 7719 // 'target' / 'teams' 7720 // 'target teams distribute parallel for' 7721 // 'target parallel' 7722 // and so on. 7723 // 7724 // Note that on the host and CPU targets, the runtime implementation of 7725 // these calls simply call the outlined function without forking threads. 7726 // The outlined functions themselves have runtime calls to 7727 // __kmpc_fork_teams() and __kmpc_fork() for this purpose, codegen'd by 7728 // the compiler in emitTeamsCall() and emitParallelCall(). 7729 // 7730 // In contrast, on the NVPTX target, the implementation of 7731 // __tgt_target_teams() launches a GPU kernel with the requested number 7732 // of teams and threads so no additional calls to the runtime are required. 7733 if (NumTeams) { 7734 // If we have NumTeams defined this means that we have an enclosed teams 7735 // region. Therefore we also expect to have NumThreads defined. These two 7736 // values should be defined in the presence of a teams directive, 7737 // regardless of having any clauses associated. If the user is using teams 7738 // but no clauses, these two values will be the default that should be 7739 // passed to the runtime library - a 32-bit integer with the value zero. 7740 assert(NumThreads && "Thread limit expression should be available along " 7741 "with number of teams."); 7742 llvm::Value *OffloadingArgs[] = {DeviceID, 7743 OutlinedFnID, 7744 PointerNum, 7745 InputInfo.BasePointersArray.getPointer(), 7746 InputInfo.PointersArray.getPointer(), 7747 InputInfo.SizesArray.getPointer(), 7748 MapTypesArray, 7749 NumTeams, 7750 NumThreads}; 7751 Return = CGF.EmitRuntimeCall( 7752 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_teams_nowait 7753 : OMPRTL__tgt_target_teams), 7754 OffloadingArgs); 7755 } else { 7756 llvm::Value *OffloadingArgs[] = {DeviceID, 7757 OutlinedFnID, 7758 PointerNum, 7759 InputInfo.BasePointersArray.getPointer(), 7760 InputInfo.PointersArray.getPointer(), 7761 InputInfo.SizesArray.getPointer(), 7762 MapTypesArray}; 7763 Return = CGF.EmitRuntimeCall( 7764 createRuntimeFunction(HasNowait ? OMPRTL__tgt_target_nowait 7765 : OMPRTL__tgt_target), 7766 OffloadingArgs); 7767 } 7768 7769 // Check the error code and execute the host version if required. 7770 llvm::BasicBlock *OffloadFailedBlock = 7771 CGF.createBasicBlock("omp_offload.failed"); 7772 llvm::BasicBlock *OffloadContBlock = 7773 CGF.createBasicBlock("omp_offload.cont"); 7774 llvm::Value *Failed = CGF.Builder.CreateIsNotNull(Return); 7775 CGF.Builder.CreateCondBr(Failed, OffloadFailedBlock, OffloadContBlock); 7776 7777 CGF.EmitBlock(OffloadFailedBlock); 7778 if (RequiresOuterTask) { 7779 CapturedVars.clear(); 7780 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars); 7781 } 7782 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars); 7783 CGF.EmitBranch(OffloadContBlock); 7784 7785 CGF.EmitBlock(OffloadContBlock, /*IsFinished=*/true); 7786 }; 7787 7788 // Notify that the host version must be executed. 7789 auto &&ElseGen = [this, &D, OutlinedFn, &CS, &CapturedVars, 7790 RequiresOuterTask](CodeGenFunction &CGF, 7791 PrePostActionTy &) { 7792 if (RequiresOuterTask) { 7793 CapturedVars.clear(); 7794 CGF.GenerateOpenMPCapturedVars(CS, CapturedVars); 7795 } 7796 emitOutlinedFunctionCall(CGF, D.getBeginLoc(), OutlinedFn, CapturedVars); 7797 }; 7798 7799 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray, 7800 &CapturedVars, RequiresOuterTask, 7801 &CS](CodeGenFunction &CGF, PrePostActionTy &) { 7802 // Fill up the arrays with all the captured variables. 7803 MappableExprsHandler::MapBaseValuesArrayTy BasePointers; 7804 MappableExprsHandler::MapValuesArrayTy Pointers; 7805 MappableExprsHandler::MapValuesArrayTy Sizes; 7806 MappableExprsHandler::MapFlagsArrayTy MapTypes; 7807 7808 // Get mappable expression information. 7809 MappableExprsHandler MEHandler(D, CGF); 7810 7811 auto RI = CS.getCapturedRecordDecl()->field_begin(); 7812 auto CV = CapturedVars.begin(); 7813 for (CapturedStmt::const_capture_iterator CI = CS.capture_begin(), 7814 CE = CS.capture_end(); 7815 CI != CE; ++CI, ++RI, ++CV) { 7816 MappableExprsHandler::MapBaseValuesArrayTy CurBasePointers; 7817 MappableExprsHandler::MapValuesArrayTy CurPointers; 7818 MappableExprsHandler::MapValuesArrayTy CurSizes; 7819 MappableExprsHandler::MapFlagsArrayTy CurMapTypes; 7820 MappableExprsHandler::StructRangeInfoTy PartialStruct; 7821 7822 // VLA sizes are passed to the outlined region by copy and do not have map 7823 // information associated. 7824 if (CI->capturesVariableArrayType()) { 7825 CurBasePointers.push_back(*CV); 7826 CurPointers.push_back(*CV); 7827 CurSizes.push_back(CGF.getTypeSize(RI->getType())); 7828 // Copy to the device as an argument. No need to retrieve it. 7829 CurMapTypes.push_back(MappableExprsHandler::OMP_MAP_LITERAL | 7830 MappableExprsHandler::OMP_MAP_TARGET_PARAM); 7831 } else { 7832 // If we have any information in the map clause, we use it, otherwise we 7833 // just do a default mapping. 7834 MEHandler.generateInfoForCapture(CI, *CV, CurBasePointers, CurPointers, 7835 CurSizes, CurMapTypes, PartialStruct); 7836 if (CurBasePointers.empty()) 7837 MEHandler.generateDefaultMapInfo(*CI, **RI, *CV, CurBasePointers, 7838 CurPointers, CurSizes, CurMapTypes); 7839 } 7840 // We expect to have at least an element of information for this capture. 7841 assert(!CurBasePointers.empty() && 7842 "Non-existing map pointer for capture!"); 7843 assert(CurBasePointers.size() == CurPointers.size() && 7844 CurBasePointers.size() == CurSizes.size() && 7845 CurBasePointers.size() == CurMapTypes.size() && 7846 "Inconsistent map information sizes!"); 7847 7848 // If there is an entry in PartialStruct it means we have a struct with 7849 // individual members mapped. Emit an extra combined entry. 7850 if (PartialStruct.Base.isValid()) 7851 MEHandler.emitCombinedEntry(BasePointers, Pointers, Sizes, MapTypes, 7852 CurMapTypes, PartialStruct); 7853 7854 // We need to append the results of this capture to what we already have. 7855 BasePointers.append(CurBasePointers.begin(), CurBasePointers.end()); 7856 Pointers.append(CurPointers.begin(), CurPointers.end()); 7857 Sizes.append(CurSizes.begin(), CurSizes.end()); 7858 MapTypes.append(CurMapTypes.begin(), CurMapTypes.end()); 7859 } 7860 // Map other list items in the map clause which are not captured variables 7861 // but "declare target link" global variables. 7862 MEHandler.generateInfoForDeclareTargetLink(BasePointers, Pointers, Sizes, 7863 MapTypes); 7864 7865 TargetDataInfo Info; 7866 // Fill up the arrays and create the arguments. 7867 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info); 7868 emitOffloadingArraysArgument(CGF, Info.BasePointersArray, 7869 Info.PointersArray, Info.SizesArray, 7870 Info.MapTypesArray, Info); 7871 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs; 7872 InputInfo.BasePointersArray = 7873 Address(Info.BasePointersArray, CGM.getPointerAlign()); 7874 InputInfo.PointersArray = 7875 Address(Info.PointersArray, CGM.getPointerAlign()); 7876 InputInfo.SizesArray = Address(Info.SizesArray, CGM.getPointerAlign()); 7877 MapTypesArray = Info.MapTypesArray; 7878 if (RequiresOuterTask) 7879 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo); 7880 else 7881 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen); 7882 }; 7883 7884 auto &&TargetElseGen = [this, &ElseGen, &D, RequiresOuterTask]( 7885 CodeGenFunction &CGF, PrePostActionTy &) { 7886 if (RequiresOuterTask) { 7887 CodeGenFunction::OMPTargetDataInfo InputInfo; 7888 CGF.EmitOMPTargetTaskBasedDirective(D, ElseGen, InputInfo); 7889 } else { 7890 emitInlinedDirective(CGF, D.getDirectiveKind(), ElseGen); 7891 } 7892 }; 7893 7894 // If we have a target function ID it means that we need to support 7895 // offloading, otherwise, just execute on the host. We need to execute on host 7896 // regardless of the conditional in the if clause if, e.g., the user do not 7897 // specify target triples. 7898 if (OutlinedFnID) { 7899 if (IfCond) { 7900 emitOMPIfClause(CGF, IfCond, TargetThenGen, TargetElseGen); 7901 } else { 7902 RegionCodeGenTy ThenRCG(TargetThenGen); 7903 ThenRCG(CGF); 7904 } 7905 } else { 7906 RegionCodeGenTy ElseRCG(TargetElseGen); 7907 ElseRCG(CGF); 7908 } 7909 } 7910 7911 void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S, 7912 StringRef ParentName) { 7913 if (!S) 7914 return; 7915 7916 // Codegen OMP target directives that offload compute to the device. 7917 bool RequiresDeviceCodegen = 7918 isa<OMPExecutableDirective>(S) && 7919 isOpenMPTargetExecutionDirective( 7920 cast<OMPExecutableDirective>(S)->getDirectiveKind()); 7921 7922 if (RequiresDeviceCodegen) { 7923 const auto &E = *cast<OMPExecutableDirective>(S); 7924 unsigned DeviceID; 7925 unsigned FileID; 7926 unsigned Line; 7927 getTargetEntryUniqueInfo(CGM.getContext(), E.getBeginLoc(), DeviceID, 7928 FileID, Line); 7929 7930 // Is this a target region that should not be emitted as an entry point? If 7931 // so just signal we are done with this target region. 7932 if (!OffloadEntriesInfoManager.hasTargetRegionEntryInfo(DeviceID, FileID, 7933 ParentName, Line)) 7934 return; 7935 7936 switch (E.getDirectiveKind()) { 7937 case OMPD_target: 7938 CodeGenFunction::EmitOMPTargetDeviceFunction(CGM, ParentName, 7939 cast<OMPTargetDirective>(E)); 7940 break; 7941 case OMPD_target_parallel: 7942 CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 7943 CGM, ParentName, cast<OMPTargetParallelDirective>(E)); 7944 break; 7945 case OMPD_target_teams: 7946 CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 7947 CGM, ParentName, cast<OMPTargetTeamsDirective>(E)); 7948 break; 7949 case OMPD_target_teams_distribute: 7950 CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 7951 CGM, ParentName, cast<OMPTargetTeamsDistributeDirective>(E)); 7952 break; 7953 case OMPD_target_teams_distribute_simd: 7954 CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 7955 CGM, ParentName, cast<OMPTargetTeamsDistributeSimdDirective>(E)); 7956 break; 7957 case OMPD_target_parallel_for: 7958 CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 7959 CGM, ParentName, cast<OMPTargetParallelForDirective>(E)); 7960 break; 7961 case OMPD_target_parallel_for_simd: 7962 CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 7963 CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E)); 7964 break; 7965 case OMPD_target_simd: 7966 CodeGenFunction::EmitOMPTargetSimdDeviceFunction( 7967 CGM, ParentName, cast<OMPTargetSimdDirective>(E)); 7968 break; 7969 case OMPD_target_teams_distribute_parallel_for: 7970 CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 7971 CGM, ParentName, 7972 cast<OMPTargetTeamsDistributeParallelForDirective>(E)); 7973 break; 7974 case OMPD_target_teams_distribute_parallel_for_simd: 7975 CodeGenFunction:: 7976 EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 7977 CGM, ParentName, 7978 cast<OMPTargetTeamsDistributeParallelForSimdDirective>(E)); 7979 break; 7980 case OMPD_parallel: 7981 case OMPD_for: 7982 case OMPD_parallel_for: 7983 case OMPD_parallel_sections: 7984 case OMPD_for_simd: 7985 case OMPD_parallel_for_simd: 7986 case OMPD_cancel: 7987 case OMPD_cancellation_point: 7988 case OMPD_ordered: 7989 case OMPD_threadprivate: 7990 case OMPD_task: 7991 case OMPD_simd: 7992 case OMPD_sections: 7993 case OMPD_section: 7994 case OMPD_single: 7995 case OMPD_master: 7996 case OMPD_critical: 7997 case OMPD_taskyield: 7998 case OMPD_barrier: 7999 case OMPD_taskwait: 8000 case OMPD_taskgroup: 8001 case OMPD_atomic: 8002 case OMPD_flush: 8003 case OMPD_teams: 8004 case OMPD_target_data: 8005 case OMPD_target_exit_data: 8006 case OMPD_target_enter_data: 8007 case OMPD_distribute: 8008 case OMPD_distribute_simd: 8009 case OMPD_distribute_parallel_for: 8010 case OMPD_distribute_parallel_for_simd: 8011 case OMPD_teams_distribute: 8012 case OMPD_teams_distribute_simd: 8013 case OMPD_teams_distribute_parallel_for: 8014 case OMPD_teams_distribute_parallel_for_simd: 8015 case OMPD_target_update: 8016 case OMPD_declare_simd: 8017 case OMPD_declare_target: 8018 case OMPD_end_declare_target: 8019 case OMPD_declare_reduction: 8020 case OMPD_taskloop: 8021 case OMPD_taskloop_simd: 8022 case OMPD_unknown: 8023 llvm_unreachable("Unknown target directive for OpenMP device codegen."); 8024 } 8025 return; 8026 } 8027 8028 if (const auto *E = dyn_cast<OMPExecutableDirective>(S)) { 8029 if (!E->hasAssociatedStmt() || !E->getAssociatedStmt()) 8030 return; 8031 8032 scanForTargetRegionsFunctions( 8033 E->getInnermostCapturedStmt()->getCapturedStmt(), ParentName); 8034 return; 8035 } 8036 8037 // If this is a lambda function, look into its body. 8038 if (const auto *L = dyn_cast<LambdaExpr>(S)) 8039 S = L->getBody(); 8040 8041 // Keep looking for target regions recursively. 8042 for (const Stmt *II : S->children()) 8043 scanForTargetRegionsFunctions(II, ParentName); 8044 } 8045 8046 bool CGOpenMPRuntime::emitTargetFunctions(GlobalDecl GD) { 8047 // If emitting code for the host, we do not process FD here. Instead we do 8048 // the normal code generation. 8049 if (!CGM.getLangOpts().OpenMPIsDevice) 8050 return false; 8051 8052 // Try to detect target regions in the function. 8053 const ValueDecl *VD = cast<ValueDecl>(GD.getDecl()); 8054 if (const auto *FD = dyn_cast<FunctionDecl>(VD)) 8055 scanForTargetRegionsFunctions(FD->getBody(), CGM.getMangledName(GD)); 8056 8057 // Do not to emit function if it is not marked as declare target. 8058 return !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) && 8059 AlreadyEmittedTargetFunctions.count(VD->getCanonicalDecl()) == 0; 8060 } 8061 8062 bool CGOpenMPRuntime::emitTargetGlobalVariable(GlobalDecl GD) { 8063 if (!CGM.getLangOpts().OpenMPIsDevice) 8064 return false; 8065 8066 // Check if there are Ctors/Dtors in this declaration and look for target 8067 // regions in it. We use the complete variant to produce the kernel name 8068 // mangling. 8069 QualType RDTy = cast<VarDecl>(GD.getDecl())->getType(); 8070 if (const auto *RD = RDTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) { 8071 for (const CXXConstructorDecl *Ctor : RD->ctors()) { 8072 StringRef ParentName = 8073 CGM.getMangledName(GlobalDecl(Ctor, Ctor_Complete)); 8074 scanForTargetRegionsFunctions(Ctor->getBody(), ParentName); 8075 } 8076 if (const CXXDestructorDecl *Dtor = RD->getDestructor()) { 8077 StringRef ParentName = 8078 CGM.getMangledName(GlobalDecl(Dtor, Dtor_Complete)); 8079 scanForTargetRegionsFunctions(Dtor->getBody(), ParentName); 8080 } 8081 } 8082 8083 // Do not to emit variable if it is not marked as declare target. 8084 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 8085 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 8086 cast<VarDecl>(GD.getDecl())); 8087 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_Link) { 8088 DeferredGlobalVariables.insert(cast<VarDecl>(GD.getDecl())); 8089 return true; 8090 } 8091 return false; 8092 } 8093 8094 void CGOpenMPRuntime::registerTargetGlobalVariable(const VarDecl *VD, 8095 llvm::Constant *Addr) { 8096 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 8097 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 8098 OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryKind Flags; 8099 StringRef VarName; 8100 CharUnits VarSize; 8101 llvm::GlobalValue::LinkageTypes Linkage; 8102 switch (*Res) { 8103 case OMPDeclareTargetDeclAttr::MT_To: 8104 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryTo; 8105 VarName = CGM.getMangledName(VD); 8106 if (VD->hasDefinition(CGM.getContext()) != VarDecl::DeclarationOnly) { 8107 VarSize = CGM.getContext().getTypeSizeInChars(VD->getType()); 8108 assert(!VarSize.isZero() && "Expected non-zero size of the variable"); 8109 } else { 8110 VarSize = CharUnits::Zero(); 8111 } 8112 Linkage = CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false); 8113 // Temp solution to prevent optimizations of the internal variables. 8114 if (CGM.getLangOpts().OpenMPIsDevice && !VD->isExternallyVisible()) { 8115 std::string RefName = getName({VarName, "ref"}); 8116 if (!CGM.GetGlobalValue(RefName)) { 8117 llvm::Constant *AddrRef = 8118 getOrCreateInternalVariable(Addr->getType(), RefName); 8119 auto *GVAddrRef = cast<llvm::GlobalVariable>(AddrRef); 8120 GVAddrRef->setConstant(/*Val=*/true); 8121 GVAddrRef->setLinkage(llvm::GlobalValue::InternalLinkage); 8122 GVAddrRef->setInitializer(Addr); 8123 CGM.addCompilerUsedGlobal(GVAddrRef); 8124 } 8125 } 8126 break; 8127 case OMPDeclareTargetDeclAttr::MT_Link: 8128 Flags = OffloadEntriesInfoManagerTy::OMPTargetGlobalVarEntryLink; 8129 if (CGM.getLangOpts().OpenMPIsDevice) { 8130 VarName = Addr->getName(); 8131 Addr = nullptr; 8132 } else { 8133 VarName = getAddrOfDeclareTargetLink(VD).getName(); 8134 Addr = 8135 cast<llvm::Constant>(getAddrOfDeclareTargetLink(VD).getPointer()); 8136 } 8137 VarSize = CGM.getPointerSize(); 8138 Linkage = llvm::GlobalValue::WeakAnyLinkage; 8139 break; 8140 } 8141 OffloadEntriesInfoManager.registerDeviceGlobalVarEntryInfo( 8142 VarName, Addr, VarSize, Flags, Linkage); 8143 } 8144 } 8145 8146 bool CGOpenMPRuntime::emitTargetGlobal(GlobalDecl GD) { 8147 if (isa<FunctionDecl>(GD.getDecl()) || 8148 isa<OMPDeclareReductionDecl>(GD.getDecl())) 8149 return emitTargetFunctions(GD); 8150 8151 return emitTargetGlobalVariable(GD); 8152 } 8153 8154 void CGOpenMPRuntime::emitDeferredTargetDecls() const { 8155 for (const VarDecl *VD : DeferredGlobalVariables) { 8156 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 8157 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 8158 if (!Res) 8159 continue; 8160 if (*Res == OMPDeclareTargetDeclAttr::MT_To) { 8161 CGM.EmitGlobal(VD); 8162 } else { 8163 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link && 8164 "Expected to or link clauses."); 8165 (void)CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD); 8166 } 8167 } 8168 } 8169 8170 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::DisableAutoDeclareTargetRAII( 8171 CodeGenModule &CGM) 8172 : CGM(CGM) { 8173 if (CGM.getLangOpts().OpenMPIsDevice) { 8174 SavedShouldMarkAsGlobal = CGM.getOpenMPRuntime().ShouldMarkAsGlobal; 8175 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = false; 8176 } 8177 } 8178 8179 CGOpenMPRuntime::DisableAutoDeclareTargetRAII::~DisableAutoDeclareTargetRAII() { 8180 if (CGM.getLangOpts().OpenMPIsDevice) 8181 CGM.getOpenMPRuntime().ShouldMarkAsGlobal = SavedShouldMarkAsGlobal; 8182 } 8183 8184 bool CGOpenMPRuntime::markAsGlobalTarget(GlobalDecl GD) { 8185 if (!CGM.getLangOpts().OpenMPIsDevice || !ShouldMarkAsGlobal) 8186 return true; 8187 8188 const auto *D = cast<FunctionDecl>(GD.getDecl()); 8189 const FunctionDecl *FD = D->getCanonicalDecl(); 8190 // Do not to emit function if it is marked as declare target as it was already 8191 // emitted. 8192 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(D)) { 8193 if (D->hasBody() && AlreadyEmittedTargetFunctions.count(FD) == 0) { 8194 if (auto *F = dyn_cast_or_null<llvm::Function>( 8195 CGM.GetGlobalValue(CGM.getMangledName(GD)))) 8196 return !F->isDeclaration(); 8197 return false; 8198 } 8199 return true; 8200 } 8201 8202 return !AlreadyEmittedTargetFunctions.insert(FD).second; 8203 } 8204 8205 llvm::Function *CGOpenMPRuntime::emitRegistrationFunction() { 8206 // If we have offloading in the current module, we need to emit the entries 8207 // now and register the offloading descriptor. 8208 createOffloadEntriesAndInfoMetadata(); 8209 8210 // Create and register the offloading binary descriptors. This is the main 8211 // entity that captures all the information about offloading in the current 8212 // compilation unit. 8213 return createOffloadingBinaryDescriptorRegistration(); 8214 } 8215 8216 void CGOpenMPRuntime::emitTeamsCall(CodeGenFunction &CGF, 8217 const OMPExecutableDirective &D, 8218 SourceLocation Loc, 8219 llvm::Value *OutlinedFn, 8220 ArrayRef<llvm::Value *> CapturedVars) { 8221 if (!CGF.HaveInsertPoint()) 8222 return; 8223 8224 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); 8225 CodeGenFunction::RunCleanupsScope Scope(CGF); 8226 8227 // Build call __kmpc_fork_teams(loc, n, microtask, var1, .., varn); 8228 llvm::Value *Args[] = { 8229 RTLoc, 8230 CGF.Builder.getInt32(CapturedVars.size()), // Number of captured vars 8231 CGF.Builder.CreateBitCast(OutlinedFn, getKmpc_MicroPointerTy())}; 8232 llvm::SmallVector<llvm::Value *, 16> RealArgs; 8233 RealArgs.append(std::begin(Args), std::end(Args)); 8234 RealArgs.append(CapturedVars.begin(), CapturedVars.end()); 8235 8236 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_fork_teams); 8237 CGF.EmitRuntimeCall(RTLFn, RealArgs); 8238 } 8239 8240 void CGOpenMPRuntime::emitNumTeamsClause(CodeGenFunction &CGF, 8241 const Expr *NumTeams, 8242 const Expr *ThreadLimit, 8243 SourceLocation Loc) { 8244 if (!CGF.HaveInsertPoint()) 8245 return; 8246 8247 llvm::Value *RTLoc = emitUpdateLocation(CGF, Loc); 8248 8249 llvm::Value *NumTeamsVal = 8250 NumTeams 8251 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(NumTeams), 8252 CGF.CGM.Int32Ty, /* isSigned = */ true) 8253 : CGF.Builder.getInt32(0); 8254 8255 llvm::Value *ThreadLimitVal = 8256 ThreadLimit 8257 ? CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(ThreadLimit), 8258 CGF.CGM.Int32Ty, /* isSigned = */ true) 8259 : CGF.Builder.getInt32(0); 8260 8261 // Build call __kmpc_push_num_teamss(&loc, global_tid, num_teams, thread_limit) 8262 llvm::Value *PushNumTeamsArgs[] = {RTLoc, getThreadID(CGF, Loc), NumTeamsVal, 8263 ThreadLimitVal}; 8264 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__kmpc_push_num_teams), 8265 PushNumTeamsArgs); 8266 } 8267 8268 void CGOpenMPRuntime::emitTargetDataCalls( 8269 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 8270 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) { 8271 if (!CGF.HaveInsertPoint()) 8272 return; 8273 8274 // Action used to replace the default codegen action and turn privatization 8275 // off. 8276 PrePostActionTy NoPrivAction; 8277 8278 // Generate the code for the opening of the data environment. Capture all the 8279 // arguments of the runtime call by reference because they are used in the 8280 // closing of the region. 8281 auto &&BeginThenGen = [this, &D, Device, &Info, 8282 &CodeGen](CodeGenFunction &CGF, PrePostActionTy &) { 8283 // Fill up the arrays with all the mapped variables. 8284 MappableExprsHandler::MapBaseValuesArrayTy BasePointers; 8285 MappableExprsHandler::MapValuesArrayTy Pointers; 8286 MappableExprsHandler::MapValuesArrayTy Sizes; 8287 MappableExprsHandler::MapFlagsArrayTy MapTypes; 8288 8289 // Get map clause information. 8290 MappableExprsHandler MCHandler(D, CGF); 8291 MCHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes); 8292 8293 // Fill up the arrays and create the arguments. 8294 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info); 8295 8296 llvm::Value *BasePointersArrayArg = nullptr; 8297 llvm::Value *PointersArrayArg = nullptr; 8298 llvm::Value *SizesArrayArg = nullptr; 8299 llvm::Value *MapTypesArrayArg = nullptr; 8300 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg, 8301 SizesArrayArg, MapTypesArrayArg, Info); 8302 8303 // Emit device ID if any. 8304 llvm::Value *DeviceID = nullptr; 8305 if (Device) { 8306 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 8307 CGF.Int64Ty, /*isSigned=*/true); 8308 } else { 8309 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 8310 } 8311 8312 // Emit the number of elements in the offloading arrays. 8313 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs); 8314 8315 llvm::Value *OffloadingArgs[] = { 8316 DeviceID, PointerNum, BasePointersArrayArg, 8317 PointersArrayArg, SizesArrayArg, MapTypesArrayArg}; 8318 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_begin), 8319 OffloadingArgs); 8320 8321 // If device pointer privatization is required, emit the body of the region 8322 // here. It will have to be duplicated: with and without privatization. 8323 if (!Info.CaptureDeviceAddrMap.empty()) 8324 CodeGen(CGF); 8325 }; 8326 8327 // Generate code for the closing of the data region. 8328 auto &&EndThenGen = [this, Device, &Info](CodeGenFunction &CGF, 8329 PrePostActionTy &) { 8330 assert(Info.isValid() && "Invalid data environment closing arguments."); 8331 8332 llvm::Value *BasePointersArrayArg = nullptr; 8333 llvm::Value *PointersArrayArg = nullptr; 8334 llvm::Value *SizesArrayArg = nullptr; 8335 llvm::Value *MapTypesArrayArg = nullptr; 8336 emitOffloadingArraysArgument(CGF, BasePointersArrayArg, PointersArrayArg, 8337 SizesArrayArg, MapTypesArrayArg, Info); 8338 8339 // Emit device ID if any. 8340 llvm::Value *DeviceID = nullptr; 8341 if (Device) { 8342 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 8343 CGF.Int64Ty, /*isSigned=*/true); 8344 } else { 8345 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 8346 } 8347 8348 // Emit the number of elements in the offloading arrays. 8349 llvm::Value *PointerNum = CGF.Builder.getInt32(Info.NumberOfPtrs); 8350 8351 llvm::Value *OffloadingArgs[] = { 8352 DeviceID, PointerNum, BasePointersArrayArg, 8353 PointersArrayArg, SizesArrayArg, MapTypesArrayArg}; 8354 CGF.EmitRuntimeCall(createRuntimeFunction(OMPRTL__tgt_target_data_end), 8355 OffloadingArgs); 8356 }; 8357 8358 // If we need device pointer privatization, we need to emit the body of the 8359 // region with no privatization in the 'else' branch of the conditional. 8360 // Otherwise, we don't have to do anything. 8361 auto &&BeginElseGen = [&Info, &CodeGen, &NoPrivAction](CodeGenFunction &CGF, 8362 PrePostActionTy &) { 8363 if (!Info.CaptureDeviceAddrMap.empty()) { 8364 CodeGen.setAction(NoPrivAction); 8365 CodeGen(CGF); 8366 } 8367 }; 8368 8369 // We don't have to do anything to close the region if the if clause evaluates 8370 // to false. 8371 auto &&EndElseGen = [](CodeGenFunction &CGF, PrePostActionTy &) {}; 8372 8373 if (IfCond) { 8374 emitOMPIfClause(CGF, IfCond, BeginThenGen, BeginElseGen); 8375 } else { 8376 RegionCodeGenTy RCG(BeginThenGen); 8377 RCG(CGF); 8378 } 8379 8380 // If we don't require privatization of device pointers, we emit the body in 8381 // between the runtime calls. This avoids duplicating the body code. 8382 if (Info.CaptureDeviceAddrMap.empty()) { 8383 CodeGen.setAction(NoPrivAction); 8384 CodeGen(CGF); 8385 } 8386 8387 if (IfCond) { 8388 emitOMPIfClause(CGF, IfCond, EndThenGen, EndElseGen); 8389 } else { 8390 RegionCodeGenTy RCG(EndThenGen); 8391 RCG(CGF); 8392 } 8393 } 8394 8395 void CGOpenMPRuntime::emitTargetDataStandAloneCall( 8396 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 8397 const Expr *Device) { 8398 if (!CGF.HaveInsertPoint()) 8399 return; 8400 8401 assert((isa<OMPTargetEnterDataDirective>(D) || 8402 isa<OMPTargetExitDataDirective>(D) || 8403 isa<OMPTargetUpdateDirective>(D)) && 8404 "Expecting either target enter, exit data, or update directives."); 8405 8406 CodeGenFunction::OMPTargetDataInfo InputInfo; 8407 llvm::Value *MapTypesArray = nullptr; 8408 // Generate the code for the opening of the data environment. 8409 auto &&ThenGen = [this, &D, Device, &InputInfo, 8410 &MapTypesArray](CodeGenFunction &CGF, PrePostActionTy &) { 8411 // Emit device ID if any. 8412 llvm::Value *DeviceID = nullptr; 8413 if (Device) { 8414 DeviceID = CGF.Builder.CreateIntCast(CGF.EmitScalarExpr(Device), 8415 CGF.Int64Ty, /*isSigned=*/true); 8416 } else { 8417 DeviceID = CGF.Builder.getInt64(OMP_DEVICEID_UNDEF); 8418 } 8419 8420 // Emit the number of elements in the offloading arrays. 8421 llvm::Constant *PointerNum = 8422 CGF.Builder.getInt32(InputInfo.NumberOfTargetItems); 8423 8424 llvm::Value *OffloadingArgs[] = {DeviceID, 8425 PointerNum, 8426 InputInfo.BasePointersArray.getPointer(), 8427 InputInfo.PointersArray.getPointer(), 8428 InputInfo.SizesArray.getPointer(), 8429 MapTypesArray}; 8430 8431 // Select the right runtime function call for each expected standalone 8432 // directive. 8433 const bool HasNowait = D.hasClausesOfKind<OMPNowaitClause>(); 8434 OpenMPRTLFunction RTLFn; 8435 switch (D.getDirectiveKind()) { 8436 case OMPD_target_enter_data: 8437 RTLFn = HasNowait ? OMPRTL__tgt_target_data_begin_nowait 8438 : OMPRTL__tgt_target_data_begin; 8439 break; 8440 case OMPD_target_exit_data: 8441 RTLFn = HasNowait ? OMPRTL__tgt_target_data_end_nowait 8442 : OMPRTL__tgt_target_data_end; 8443 break; 8444 case OMPD_target_update: 8445 RTLFn = HasNowait ? OMPRTL__tgt_target_data_update_nowait 8446 : OMPRTL__tgt_target_data_update; 8447 break; 8448 case OMPD_parallel: 8449 case OMPD_for: 8450 case OMPD_parallel_for: 8451 case OMPD_parallel_sections: 8452 case OMPD_for_simd: 8453 case OMPD_parallel_for_simd: 8454 case OMPD_cancel: 8455 case OMPD_cancellation_point: 8456 case OMPD_ordered: 8457 case OMPD_threadprivate: 8458 case OMPD_task: 8459 case OMPD_simd: 8460 case OMPD_sections: 8461 case OMPD_section: 8462 case OMPD_single: 8463 case OMPD_master: 8464 case OMPD_critical: 8465 case OMPD_taskyield: 8466 case OMPD_barrier: 8467 case OMPD_taskwait: 8468 case OMPD_taskgroup: 8469 case OMPD_atomic: 8470 case OMPD_flush: 8471 case OMPD_teams: 8472 case OMPD_target_data: 8473 case OMPD_distribute: 8474 case OMPD_distribute_simd: 8475 case OMPD_distribute_parallel_for: 8476 case OMPD_distribute_parallel_for_simd: 8477 case OMPD_teams_distribute: 8478 case OMPD_teams_distribute_simd: 8479 case OMPD_teams_distribute_parallel_for: 8480 case OMPD_teams_distribute_parallel_for_simd: 8481 case OMPD_declare_simd: 8482 case OMPD_declare_target: 8483 case OMPD_end_declare_target: 8484 case OMPD_declare_reduction: 8485 case OMPD_taskloop: 8486 case OMPD_taskloop_simd: 8487 case OMPD_target: 8488 case OMPD_target_simd: 8489 case OMPD_target_teams_distribute: 8490 case OMPD_target_teams_distribute_simd: 8491 case OMPD_target_teams_distribute_parallel_for: 8492 case OMPD_target_teams_distribute_parallel_for_simd: 8493 case OMPD_target_teams: 8494 case OMPD_target_parallel: 8495 case OMPD_target_parallel_for: 8496 case OMPD_target_parallel_for_simd: 8497 case OMPD_unknown: 8498 llvm_unreachable("Unexpected standalone target data directive."); 8499 break; 8500 } 8501 CGF.EmitRuntimeCall(createRuntimeFunction(RTLFn), OffloadingArgs); 8502 }; 8503 8504 auto &&TargetThenGen = [this, &ThenGen, &D, &InputInfo, &MapTypesArray]( 8505 CodeGenFunction &CGF, PrePostActionTy &) { 8506 // Fill up the arrays with all the mapped variables. 8507 MappableExprsHandler::MapBaseValuesArrayTy BasePointers; 8508 MappableExprsHandler::MapValuesArrayTy Pointers; 8509 MappableExprsHandler::MapValuesArrayTy Sizes; 8510 MappableExprsHandler::MapFlagsArrayTy MapTypes; 8511 8512 // Get map clause information. 8513 MappableExprsHandler MEHandler(D, CGF); 8514 MEHandler.generateAllInfo(BasePointers, Pointers, Sizes, MapTypes); 8515 8516 TargetDataInfo Info; 8517 // Fill up the arrays and create the arguments. 8518 emitOffloadingArrays(CGF, BasePointers, Pointers, Sizes, MapTypes, Info); 8519 emitOffloadingArraysArgument(CGF, Info.BasePointersArray, 8520 Info.PointersArray, Info.SizesArray, 8521 Info.MapTypesArray, Info); 8522 InputInfo.NumberOfTargetItems = Info.NumberOfPtrs; 8523 InputInfo.BasePointersArray = 8524 Address(Info.BasePointersArray, CGM.getPointerAlign()); 8525 InputInfo.PointersArray = 8526 Address(Info.PointersArray, CGM.getPointerAlign()); 8527 InputInfo.SizesArray = 8528 Address(Info.SizesArray, CGM.getPointerAlign()); 8529 MapTypesArray = Info.MapTypesArray; 8530 if (D.hasClausesOfKind<OMPDependClause>()) 8531 CGF.EmitOMPTargetTaskBasedDirective(D, ThenGen, InputInfo); 8532 else 8533 emitInlinedDirective(CGF, D.getDirectiveKind(), ThenGen); 8534 }; 8535 8536 if (IfCond) { 8537 emitOMPIfClause(CGF, IfCond, TargetThenGen, 8538 [](CodeGenFunction &CGF, PrePostActionTy &) {}); 8539 } else { 8540 RegionCodeGenTy ThenRCG(TargetThenGen); 8541 ThenRCG(CGF); 8542 } 8543 } 8544 8545 namespace { 8546 /// Kind of parameter in a function with 'declare simd' directive. 8547 enum ParamKindTy { LinearWithVarStride, Linear, Uniform, Vector }; 8548 /// Attribute set of the parameter. 8549 struct ParamAttrTy { 8550 ParamKindTy Kind = Vector; 8551 llvm::APSInt StrideOrArg; 8552 llvm::APSInt Alignment; 8553 }; 8554 } // namespace 8555 8556 static unsigned evaluateCDTSize(const FunctionDecl *FD, 8557 ArrayRef<ParamAttrTy> ParamAttrs) { 8558 // Every vector variant of a SIMD-enabled function has a vector length (VLEN). 8559 // If OpenMP clause "simdlen" is used, the VLEN is the value of the argument 8560 // of that clause. The VLEN value must be power of 2. 8561 // In other case the notion of the function`s "characteristic data type" (CDT) 8562 // is used to compute the vector length. 8563 // CDT is defined in the following order: 8564 // a) For non-void function, the CDT is the return type. 8565 // b) If the function has any non-uniform, non-linear parameters, then the 8566 // CDT is the type of the first such parameter. 8567 // c) If the CDT determined by a) or b) above is struct, union, or class 8568 // type which is pass-by-value (except for the type that maps to the 8569 // built-in complex data type), the characteristic data type is int. 8570 // d) If none of the above three cases is applicable, the CDT is int. 8571 // The VLEN is then determined based on the CDT and the size of vector 8572 // register of that ISA for which current vector version is generated. The 8573 // VLEN is computed using the formula below: 8574 // VLEN = sizeof(vector_register) / sizeof(CDT), 8575 // where vector register size specified in section 3.2.1 Registers and the 8576 // Stack Frame of original AMD64 ABI document. 8577 QualType RetType = FD->getReturnType(); 8578 if (RetType.isNull()) 8579 return 0; 8580 ASTContext &C = FD->getASTContext(); 8581 QualType CDT; 8582 if (!RetType.isNull() && !RetType->isVoidType()) { 8583 CDT = RetType; 8584 } else { 8585 unsigned Offset = 0; 8586 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 8587 if (ParamAttrs[Offset].Kind == Vector) 8588 CDT = C.getPointerType(C.getRecordType(MD->getParent())); 8589 ++Offset; 8590 } 8591 if (CDT.isNull()) { 8592 for (unsigned I = 0, E = FD->getNumParams(); I < E; ++I) { 8593 if (ParamAttrs[I + Offset].Kind == Vector) { 8594 CDT = FD->getParamDecl(I)->getType(); 8595 break; 8596 } 8597 } 8598 } 8599 } 8600 if (CDT.isNull()) 8601 CDT = C.IntTy; 8602 CDT = CDT->getCanonicalTypeUnqualified(); 8603 if (CDT->isRecordType() || CDT->isUnionType()) 8604 CDT = C.IntTy; 8605 return C.getTypeSize(CDT); 8606 } 8607 8608 static void 8609 emitX86DeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn, 8610 const llvm::APSInt &VLENVal, 8611 ArrayRef<ParamAttrTy> ParamAttrs, 8612 OMPDeclareSimdDeclAttr::BranchStateTy State) { 8613 struct ISADataTy { 8614 char ISA; 8615 unsigned VecRegSize; 8616 }; 8617 ISADataTy ISAData[] = { 8618 { 8619 'b', 128 8620 }, // SSE 8621 { 8622 'c', 256 8623 }, // AVX 8624 { 8625 'd', 256 8626 }, // AVX2 8627 { 8628 'e', 512 8629 }, // AVX512 8630 }; 8631 llvm::SmallVector<char, 2> Masked; 8632 switch (State) { 8633 case OMPDeclareSimdDeclAttr::BS_Undefined: 8634 Masked.push_back('N'); 8635 Masked.push_back('M'); 8636 break; 8637 case OMPDeclareSimdDeclAttr::BS_Notinbranch: 8638 Masked.push_back('N'); 8639 break; 8640 case OMPDeclareSimdDeclAttr::BS_Inbranch: 8641 Masked.push_back('M'); 8642 break; 8643 } 8644 for (char Mask : Masked) { 8645 for (const ISADataTy &Data : ISAData) { 8646 SmallString<256> Buffer; 8647 llvm::raw_svector_ostream Out(Buffer); 8648 Out << "_ZGV" << Data.ISA << Mask; 8649 if (!VLENVal) { 8650 Out << llvm::APSInt::getUnsigned(Data.VecRegSize / 8651 evaluateCDTSize(FD, ParamAttrs)); 8652 } else { 8653 Out << VLENVal; 8654 } 8655 for (const ParamAttrTy &ParamAttr : ParamAttrs) { 8656 switch (ParamAttr.Kind){ 8657 case LinearWithVarStride: 8658 Out << 's' << ParamAttr.StrideOrArg; 8659 break; 8660 case Linear: 8661 Out << 'l'; 8662 if (!!ParamAttr.StrideOrArg) 8663 Out << ParamAttr.StrideOrArg; 8664 break; 8665 case Uniform: 8666 Out << 'u'; 8667 break; 8668 case Vector: 8669 Out << 'v'; 8670 break; 8671 } 8672 if (!!ParamAttr.Alignment) 8673 Out << 'a' << ParamAttr.Alignment; 8674 } 8675 Out << '_' << Fn->getName(); 8676 Fn->addFnAttr(Out.str()); 8677 } 8678 } 8679 } 8680 8681 void CGOpenMPRuntime::emitDeclareSimdFunction(const FunctionDecl *FD, 8682 llvm::Function *Fn) { 8683 ASTContext &C = CGM.getContext(); 8684 FD = FD->getMostRecentDecl(); 8685 // Map params to their positions in function decl. 8686 llvm::DenseMap<const Decl *, unsigned> ParamPositions; 8687 if (isa<CXXMethodDecl>(FD)) 8688 ParamPositions.try_emplace(FD, 0); 8689 unsigned ParamPos = ParamPositions.size(); 8690 for (const ParmVarDecl *P : FD->parameters()) { 8691 ParamPositions.try_emplace(P->getCanonicalDecl(), ParamPos); 8692 ++ParamPos; 8693 } 8694 while (FD) { 8695 for (const auto *Attr : FD->specific_attrs<OMPDeclareSimdDeclAttr>()) { 8696 llvm::SmallVector<ParamAttrTy, 8> ParamAttrs(ParamPositions.size()); 8697 // Mark uniform parameters. 8698 for (const Expr *E : Attr->uniforms()) { 8699 E = E->IgnoreParenImpCasts(); 8700 unsigned Pos; 8701 if (isa<CXXThisExpr>(E)) { 8702 Pos = ParamPositions[FD]; 8703 } else { 8704 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl()) 8705 ->getCanonicalDecl(); 8706 Pos = ParamPositions[PVD]; 8707 } 8708 ParamAttrs[Pos].Kind = Uniform; 8709 } 8710 // Get alignment info. 8711 auto NI = Attr->alignments_begin(); 8712 for (const Expr *E : Attr->aligneds()) { 8713 E = E->IgnoreParenImpCasts(); 8714 unsigned Pos; 8715 QualType ParmTy; 8716 if (isa<CXXThisExpr>(E)) { 8717 Pos = ParamPositions[FD]; 8718 ParmTy = E->getType(); 8719 } else { 8720 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl()) 8721 ->getCanonicalDecl(); 8722 Pos = ParamPositions[PVD]; 8723 ParmTy = PVD->getType(); 8724 } 8725 ParamAttrs[Pos].Alignment = 8726 (*NI) 8727 ? (*NI)->EvaluateKnownConstInt(C) 8728 : llvm::APSInt::getUnsigned( 8729 C.toCharUnitsFromBits(C.getOpenMPDefaultSimdAlign(ParmTy)) 8730 .getQuantity()); 8731 ++NI; 8732 } 8733 // Mark linear parameters. 8734 auto SI = Attr->steps_begin(); 8735 auto MI = Attr->modifiers_begin(); 8736 for (const Expr *E : Attr->linears()) { 8737 E = E->IgnoreParenImpCasts(); 8738 unsigned Pos; 8739 if (isa<CXXThisExpr>(E)) { 8740 Pos = ParamPositions[FD]; 8741 } else { 8742 const auto *PVD = cast<ParmVarDecl>(cast<DeclRefExpr>(E)->getDecl()) 8743 ->getCanonicalDecl(); 8744 Pos = ParamPositions[PVD]; 8745 } 8746 ParamAttrTy &ParamAttr = ParamAttrs[Pos]; 8747 ParamAttr.Kind = Linear; 8748 if (*SI) { 8749 if (!(*SI)->EvaluateAsInt(ParamAttr.StrideOrArg, C, 8750 Expr::SE_AllowSideEffects)) { 8751 if (const auto *DRE = 8752 cast<DeclRefExpr>((*SI)->IgnoreParenImpCasts())) { 8753 if (const auto *StridePVD = cast<ParmVarDecl>(DRE->getDecl())) { 8754 ParamAttr.Kind = LinearWithVarStride; 8755 ParamAttr.StrideOrArg = llvm::APSInt::getUnsigned( 8756 ParamPositions[StridePVD->getCanonicalDecl()]); 8757 } 8758 } 8759 } 8760 } 8761 ++SI; 8762 ++MI; 8763 } 8764 llvm::APSInt VLENVal; 8765 if (const Expr *VLEN = Attr->getSimdlen()) 8766 VLENVal = VLEN->EvaluateKnownConstInt(C); 8767 OMPDeclareSimdDeclAttr::BranchStateTy State = Attr->getBranchState(); 8768 if (CGM.getTriple().getArch() == llvm::Triple::x86 || 8769 CGM.getTriple().getArch() == llvm::Triple::x86_64) 8770 emitX86DeclareSimdFunction(FD, Fn, VLENVal, ParamAttrs, State); 8771 } 8772 FD = FD->getPreviousDecl(); 8773 } 8774 } 8775 8776 namespace { 8777 /// Cleanup action for doacross support. 8778 class DoacrossCleanupTy final : public EHScopeStack::Cleanup { 8779 public: 8780 static const int DoacrossFinArgs = 2; 8781 8782 private: 8783 llvm::Value *RTLFn; 8784 llvm::Value *Args[DoacrossFinArgs]; 8785 8786 public: 8787 DoacrossCleanupTy(llvm::Value *RTLFn, ArrayRef<llvm::Value *> CallArgs) 8788 : RTLFn(RTLFn) { 8789 assert(CallArgs.size() == DoacrossFinArgs); 8790 std::copy(CallArgs.begin(), CallArgs.end(), std::begin(Args)); 8791 } 8792 void Emit(CodeGenFunction &CGF, Flags /*flags*/) override { 8793 if (!CGF.HaveInsertPoint()) 8794 return; 8795 CGF.EmitRuntimeCall(RTLFn, Args); 8796 } 8797 }; 8798 } // namespace 8799 8800 void CGOpenMPRuntime::emitDoacrossInit(CodeGenFunction &CGF, 8801 const OMPLoopDirective &D, 8802 ArrayRef<Expr *> NumIterations) { 8803 if (!CGF.HaveInsertPoint()) 8804 return; 8805 8806 ASTContext &C = CGM.getContext(); 8807 QualType Int64Ty = C.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/true); 8808 RecordDecl *RD; 8809 if (KmpDimTy.isNull()) { 8810 // Build struct kmp_dim { // loop bounds info casted to kmp_int64 8811 // kmp_int64 lo; // lower 8812 // kmp_int64 up; // upper 8813 // kmp_int64 st; // stride 8814 // }; 8815 RD = C.buildImplicitRecord("kmp_dim"); 8816 RD->startDefinition(); 8817 addFieldToRecordDecl(C, RD, Int64Ty); 8818 addFieldToRecordDecl(C, RD, Int64Ty); 8819 addFieldToRecordDecl(C, RD, Int64Ty); 8820 RD->completeDefinition(); 8821 KmpDimTy = C.getRecordType(RD); 8822 } else { 8823 RD = cast<RecordDecl>(KmpDimTy->getAsTagDecl()); 8824 } 8825 llvm::APInt Size(/*numBits=*/32, NumIterations.size()); 8826 QualType ArrayTy = 8827 C.getConstantArrayType(KmpDimTy, Size, ArrayType::Normal, 0); 8828 8829 Address DimsAddr = CGF.CreateMemTemp(ArrayTy, "dims"); 8830 CGF.EmitNullInitialization(DimsAddr, ArrayTy); 8831 enum { LowerFD = 0, UpperFD, StrideFD }; 8832 // Fill dims with data. 8833 for (unsigned I = 0, E = NumIterations.size(); I < E; ++I) { 8834 LValue DimsLVal = 8835 CGF.MakeAddrLValue(CGF.Builder.CreateConstArrayGEP( 8836 DimsAddr, I, C.getTypeSizeInChars(KmpDimTy)), 8837 KmpDimTy); 8838 // dims.upper = num_iterations; 8839 LValue UpperLVal = CGF.EmitLValueForField( 8840 DimsLVal, *std::next(RD->field_begin(), UpperFD)); 8841 llvm::Value *NumIterVal = 8842 CGF.EmitScalarConversion(CGF.EmitScalarExpr(NumIterations[I]), 8843 D.getNumIterations()->getType(), Int64Ty, 8844 D.getNumIterations()->getExprLoc()); 8845 CGF.EmitStoreOfScalar(NumIterVal, UpperLVal); 8846 // dims.stride = 1; 8847 LValue StrideLVal = CGF.EmitLValueForField( 8848 DimsLVal, *std::next(RD->field_begin(), StrideFD)); 8849 CGF.EmitStoreOfScalar(llvm::ConstantInt::getSigned(CGM.Int64Ty, /*V=*/1), 8850 StrideLVal); 8851 } 8852 8853 // Build call void __kmpc_doacross_init(ident_t *loc, kmp_int32 gtid, 8854 // kmp_int32 num_dims, struct kmp_dim * dims); 8855 llvm::Value *Args[] = { 8856 emitUpdateLocation(CGF, D.getBeginLoc()), 8857 getThreadID(CGF, D.getBeginLoc()), 8858 llvm::ConstantInt::getSigned(CGM.Int32Ty, NumIterations.size()), 8859 CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 8860 CGF.Builder 8861 .CreateConstArrayGEP(DimsAddr, 0, C.getTypeSizeInChars(KmpDimTy)) 8862 .getPointer(), 8863 CGM.VoidPtrTy)}; 8864 8865 llvm::Value *RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_init); 8866 CGF.EmitRuntimeCall(RTLFn, Args); 8867 llvm::Value *FiniArgs[DoacrossCleanupTy::DoacrossFinArgs] = { 8868 emitUpdateLocation(CGF, D.getEndLoc()), getThreadID(CGF, D.getEndLoc())}; 8869 llvm::Value *FiniRTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_fini); 8870 CGF.EHStack.pushCleanup<DoacrossCleanupTy>(NormalAndEHCleanup, FiniRTLFn, 8871 llvm::makeArrayRef(FiniArgs)); 8872 } 8873 8874 void CGOpenMPRuntime::emitDoacrossOrdered(CodeGenFunction &CGF, 8875 const OMPDependClause *C) { 8876 QualType Int64Ty = 8877 CGM.getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 8878 llvm::APInt Size(/*numBits=*/32, C->getNumLoops()); 8879 QualType ArrayTy = CGM.getContext().getConstantArrayType( 8880 Int64Ty, Size, ArrayType::Normal, 0); 8881 Address CntAddr = CGF.CreateMemTemp(ArrayTy, ".cnt.addr"); 8882 for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I) { 8883 const Expr *CounterVal = C->getLoopData(I); 8884 assert(CounterVal); 8885 llvm::Value *CntVal = CGF.EmitScalarConversion( 8886 CGF.EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty, 8887 CounterVal->getExprLoc()); 8888 CGF.EmitStoreOfScalar( 8889 CntVal, 8890 CGF.Builder.CreateConstArrayGEP( 8891 CntAddr, I, CGM.getContext().getTypeSizeInChars(Int64Ty)), 8892 /*Volatile=*/false, Int64Ty); 8893 } 8894 llvm::Value *Args[] = { 8895 emitUpdateLocation(CGF, C->getBeginLoc()), 8896 getThreadID(CGF, C->getBeginLoc()), 8897 CGF.Builder 8898 .CreateConstArrayGEP(CntAddr, 0, 8899 CGM.getContext().getTypeSizeInChars(Int64Ty)) 8900 .getPointer()}; 8901 llvm::Value *RTLFn; 8902 if (C->getDependencyKind() == OMPC_DEPEND_source) { 8903 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_post); 8904 } else { 8905 assert(C->getDependencyKind() == OMPC_DEPEND_sink); 8906 RTLFn = createRuntimeFunction(OMPRTL__kmpc_doacross_wait); 8907 } 8908 CGF.EmitRuntimeCall(RTLFn, Args); 8909 } 8910 8911 void CGOpenMPRuntime::emitCall(CodeGenFunction &CGF, SourceLocation Loc, 8912 llvm::Value *Callee, 8913 ArrayRef<llvm::Value *> Args) const { 8914 assert(Loc.isValid() && "Outlined function call location must be valid."); 8915 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, Loc); 8916 8917 if (auto *Fn = dyn_cast<llvm::Function>(Callee)) { 8918 if (Fn->doesNotThrow()) { 8919 CGF.EmitNounwindRuntimeCall(Fn, Args); 8920 return; 8921 } 8922 } 8923 CGF.EmitRuntimeCall(Callee, Args); 8924 } 8925 8926 void CGOpenMPRuntime::emitOutlinedFunctionCall( 8927 CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *OutlinedFn, 8928 ArrayRef<llvm::Value *> Args) const { 8929 emitCall(CGF, Loc, OutlinedFn, Args); 8930 } 8931 8932 Address CGOpenMPRuntime::getParameterAddress(CodeGenFunction &CGF, 8933 const VarDecl *NativeParam, 8934 const VarDecl *TargetParam) const { 8935 return CGF.GetAddrOfLocalVar(NativeParam); 8936 } 8937 8938 Address CGOpenMPRuntime::getAddressOfLocalVariable(CodeGenFunction &CGF, 8939 const VarDecl *VD) { 8940 return Address::invalid(); 8941 } 8942 8943 llvm::Value *CGOpenMPSIMDRuntime::emitParallelOutlinedFunction( 8944 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 8945 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 8946 llvm_unreachable("Not supported in SIMD-only mode"); 8947 } 8948 8949 llvm::Value *CGOpenMPSIMDRuntime::emitTeamsOutlinedFunction( 8950 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 8951 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) { 8952 llvm_unreachable("Not supported in SIMD-only mode"); 8953 } 8954 8955 llvm::Value *CGOpenMPSIMDRuntime::emitTaskOutlinedFunction( 8956 const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, 8957 const VarDecl *PartIDVar, const VarDecl *TaskTVar, 8958 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 8959 bool Tied, unsigned &NumberOfParts) { 8960 llvm_unreachable("Not supported in SIMD-only mode"); 8961 } 8962 8963 void CGOpenMPSIMDRuntime::emitParallelCall(CodeGenFunction &CGF, 8964 SourceLocation Loc, 8965 llvm::Value *OutlinedFn, 8966 ArrayRef<llvm::Value *> CapturedVars, 8967 const Expr *IfCond) { 8968 llvm_unreachable("Not supported in SIMD-only mode"); 8969 } 8970 8971 void CGOpenMPSIMDRuntime::emitCriticalRegion( 8972 CodeGenFunction &CGF, StringRef CriticalName, 8973 const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, 8974 const Expr *Hint) { 8975 llvm_unreachable("Not supported in SIMD-only mode"); 8976 } 8977 8978 void CGOpenMPSIMDRuntime::emitMasterRegion(CodeGenFunction &CGF, 8979 const RegionCodeGenTy &MasterOpGen, 8980 SourceLocation Loc) { 8981 llvm_unreachable("Not supported in SIMD-only mode"); 8982 } 8983 8984 void CGOpenMPSIMDRuntime::emitTaskyieldCall(CodeGenFunction &CGF, 8985 SourceLocation Loc) { 8986 llvm_unreachable("Not supported in SIMD-only mode"); 8987 } 8988 8989 void CGOpenMPSIMDRuntime::emitTaskgroupRegion( 8990 CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, 8991 SourceLocation Loc) { 8992 llvm_unreachable("Not supported in SIMD-only mode"); 8993 } 8994 8995 void CGOpenMPSIMDRuntime::emitSingleRegion( 8996 CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, 8997 SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, 8998 ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, 8999 ArrayRef<const Expr *> AssignmentOps) { 9000 llvm_unreachable("Not supported in SIMD-only mode"); 9001 } 9002 9003 void CGOpenMPSIMDRuntime::emitOrderedRegion(CodeGenFunction &CGF, 9004 const RegionCodeGenTy &OrderedOpGen, 9005 SourceLocation Loc, 9006 bool IsThreads) { 9007 llvm_unreachable("Not supported in SIMD-only mode"); 9008 } 9009 9010 void CGOpenMPSIMDRuntime::emitBarrierCall(CodeGenFunction &CGF, 9011 SourceLocation Loc, 9012 OpenMPDirectiveKind Kind, 9013 bool EmitChecks, 9014 bool ForceSimpleCall) { 9015 llvm_unreachable("Not supported in SIMD-only mode"); 9016 } 9017 9018 void CGOpenMPSIMDRuntime::emitForDispatchInit( 9019 CodeGenFunction &CGF, SourceLocation Loc, 9020 const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, 9021 bool Ordered, const DispatchRTInput &DispatchValues) { 9022 llvm_unreachable("Not supported in SIMD-only mode"); 9023 } 9024 9025 void CGOpenMPSIMDRuntime::emitForStaticInit( 9026 CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, 9027 const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) { 9028 llvm_unreachable("Not supported in SIMD-only mode"); 9029 } 9030 9031 void CGOpenMPSIMDRuntime::emitDistributeStaticInit( 9032 CodeGenFunction &CGF, SourceLocation Loc, 9033 OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) { 9034 llvm_unreachable("Not supported in SIMD-only mode"); 9035 } 9036 9037 void CGOpenMPSIMDRuntime::emitForOrderedIterationEnd(CodeGenFunction &CGF, 9038 SourceLocation Loc, 9039 unsigned IVSize, 9040 bool IVSigned) { 9041 llvm_unreachable("Not supported in SIMD-only mode"); 9042 } 9043 9044 void CGOpenMPSIMDRuntime::emitForStaticFinish(CodeGenFunction &CGF, 9045 SourceLocation Loc, 9046 OpenMPDirectiveKind DKind) { 9047 llvm_unreachable("Not supported in SIMD-only mode"); 9048 } 9049 9050 llvm::Value *CGOpenMPSIMDRuntime::emitForNext(CodeGenFunction &CGF, 9051 SourceLocation Loc, 9052 unsigned IVSize, bool IVSigned, 9053 Address IL, Address LB, 9054 Address UB, Address ST) { 9055 llvm_unreachable("Not supported in SIMD-only mode"); 9056 } 9057 9058 void CGOpenMPSIMDRuntime::emitNumThreadsClause(CodeGenFunction &CGF, 9059 llvm::Value *NumThreads, 9060 SourceLocation Loc) { 9061 llvm_unreachable("Not supported in SIMD-only mode"); 9062 } 9063 9064 void CGOpenMPSIMDRuntime::emitProcBindClause(CodeGenFunction &CGF, 9065 OpenMPProcBindClauseKind ProcBind, 9066 SourceLocation Loc) { 9067 llvm_unreachable("Not supported in SIMD-only mode"); 9068 } 9069 9070 Address CGOpenMPSIMDRuntime::getAddrOfThreadPrivate(CodeGenFunction &CGF, 9071 const VarDecl *VD, 9072 Address VDAddr, 9073 SourceLocation Loc) { 9074 llvm_unreachable("Not supported in SIMD-only mode"); 9075 } 9076 9077 llvm::Function *CGOpenMPSIMDRuntime::emitThreadPrivateVarDefinition( 9078 const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, 9079 CodeGenFunction *CGF) { 9080 llvm_unreachable("Not supported in SIMD-only mode"); 9081 } 9082 9083 Address CGOpenMPSIMDRuntime::getAddrOfArtificialThreadPrivate( 9084 CodeGenFunction &CGF, QualType VarType, StringRef Name) { 9085 llvm_unreachable("Not supported in SIMD-only mode"); 9086 } 9087 9088 void CGOpenMPSIMDRuntime::emitFlush(CodeGenFunction &CGF, 9089 ArrayRef<const Expr *> Vars, 9090 SourceLocation Loc) { 9091 llvm_unreachable("Not supported in SIMD-only mode"); 9092 } 9093 9094 void CGOpenMPSIMDRuntime::emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, 9095 const OMPExecutableDirective &D, 9096 llvm::Value *TaskFunction, 9097 QualType SharedsTy, Address Shareds, 9098 const Expr *IfCond, 9099 const OMPTaskDataTy &Data) { 9100 llvm_unreachable("Not supported in SIMD-only mode"); 9101 } 9102 9103 void CGOpenMPSIMDRuntime::emitTaskLoopCall( 9104 CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, 9105 llvm::Value *TaskFunction, QualType SharedsTy, Address Shareds, 9106 const Expr *IfCond, const OMPTaskDataTy &Data) { 9107 llvm_unreachable("Not supported in SIMD-only mode"); 9108 } 9109 9110 void CGOpenMPSIMDRuntime::emitReduction( 9111 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, 9112 ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, 9113 ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) { 9114 assert(Options.SimpleReduction && "Only simple reduction is expected."); 9115 CGOpenMPRuntime::emitReduction(CGF, Loc, Privates, LHSExprs, RHSExprs, 9116 ReductionOps, Options); 9117 } 9118 9119 llvm::Value *CGOpenMPSIMDRuntime::emitTaskReductionInit( 9120 CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, 9121 ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) { 9122 llvm_unreachable("Not supported in SIMD-only mode"); 9123 } 9124 9125 void CGOpenMPSIMDRuntime::emitTaskReductionFixups(CodeGenFunction &CGF, 9126 SourceLocation Loc, 9127 ReductionCodeGen &RCG, 9128 unsigned N) { 9129 llvm_unreachable("Not supported in SIMD-only mode"); 9130 } 9131 9132 Address CGOpenMPSIMDRuntime::getTaskReductionItem(CodeGenFunction &CGF, 9133 SourceLocation Loc, 9134 llvm::Value *ReductionsPtr, 9135 LValue SharedLVal) { 9136 llvm_unreachable("Not supported in SIMD-only mode"); 9137 } 9138 9139 void CGOpenMPSIMDRuntime::emitTaskwaitCall(CodeGenFunction &CGF, 9140 SourceLocation Loc) { 9141 llvm_unreachable("Not supported in SIMD-only mode"); 9142 } 9143 9144 void CGOpenMPSIMDRuntime::emitCancellationPointCall( 9145 CodeGenFunction &CGF, SourceLocation Loc, 9146 OpenMPDirectiveKind CancelRegion) { 9147 llvm_unreachable("Not supported in SIMD-only mode"); 9148 } 9149 9150 void CGOpenMPSIMDRuntime::emitCancelCall(CodeGenFunction &CGF, 9151 SourceLocation Loc, const Expr *IfCond, 9152 OpenMPDirectiveKind CancelRegion) { 9153 llvm_unreachable("Not supported in SIMD-only mode"); 9154 } 9155 9156 void CGOpenMPSIMDRuntime::emitTargetOutlinedFunction( 9157 const OMPExecutableDirective &D, StringRef ParentName, 9158 llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, 9159 bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) { 9160 llvm_unreachable("Not supported in SIMD-only mode"); 9161 } 9162 9163 void CGOpenMPSIMDRuntime::emitTargetCall(CodeGenFunction &CGF, 9164 const OMPExecutableDirective &D, 9165 llvm::Value *OutlinedFn, 9166 llvm::Value *OutlinedFnID, 9167 const Expr *IfCond, const Expr *Device) { 9168 llvm_unreachable("Not supported in SIMD-only mode"); 9169 } 9170 9171 bool CGOpenMPSIMDRuntime::emitTargetFunctions(GlobalDecl GD) { 9172 llvm_unreachable("Not supported in SIMD-only mode"); 9173 } 9174 9175 bool CGOpenMPSIMDRuntime::emitTargetGlobalVariable(GlobalDecl GD) { 9176 llvm_unreachable("Not supported in SIMD-only mode"); 9177 } 9178 9179 bool CGOpenMPSIMDRuntime::emitTargetGlobal(GlobalDecl GD) { 9180 return false; 9181 } 9182 9183 llvm::Function *CGOpenMPSIMDRuntime::emitRegistrationFunction() { 9184 return nullptr; 9185 } 9186 9187 void CGOpenMPSIMDRuntime::emitTeamsCall(CodeGenFunction &CGF, 9188 const OMPExecutableDirective &D, 9189 SourceLocation Loc, 9190 llvm::Value *OutlinedFn, 9191 ArrayRef<llvm::Value *> CapturedVars) { 9192 llvm_unreachable("Not supported in SIMD-only mode"); 9193 } 9194 9195 void CGOpenMPSIMDRuntime::emitNumTeamsClause(CodeGenFunction &CGF, 9196 const Expr *NumTeams, 9197 const Expr *ThreadLimit, 9198 SourceLocation Loc) { 9199 llvm_unreachable("Not supported in SIMD-only mode"); 9200 } 9201 9202 void CGOpenMPSIMDRuntime::emitTargetDataCalls( 9203 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 9204 const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) { 9205 llvm_unreachable("Not supported in SIMD-only mode"); 9206 } 9207 9208 void CGOpenMPSIMDRuntime::emitTargetDataStandAloneCall( 9209 CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, 9210 const Expr *Device) { 9211 llvm_unreachable("Not supported in SIMD-only mode"); 9212 } 9213 9214 void CGOpenMPSIMDRuntime::emitDoacrossInit(CodeGenFunction &CGF, 9215 const OMPLoopDirective &D, 9216 ArrayRef<Expr *> NumIterations) { 9217 llvm_unreachable("Not supported in SIMD-only mode"); 9218 } 9219 9220 void CGOpenMPSIMDRuntime::emitDoacrossOrdered(CodeGenFunction &CGF, 9221 const OMPDependClause *C) { 9222 llvm_unreachable("Not supported in SIMD-only mode"); 9223 } 9224 9225 const VarDecl * 9226 CGOpenMPSIMDRuntime::translateParameter(const FieldDecl *FD, 9227 const VarDecl *NativeParam) const { 9228 llvm_unreachable("Not supported in SIMD-only mode"); 9229 } 9230 9231 Address 9232 CGOpenMPSIMDRuntime::getParameterAddress(CodeGenFunction &CGF, 9233 const VarDecl *NativeParam, 9234 const VarDecl *TargetParam) const { 9235 llvm_unreachable("Not supported in SIMD-only mode"); 9236 } 9237 9238