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