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