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