1 //===--- CGStmtOpenMP.cpp - Emit LLVM Code from Statements ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This contains code to emit OpenMP nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCleanup.h" 14 #include "CGOpenMPRuntime.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "TargetInfo.h" 18 #include "clang/AST/ASTContext.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/OpenMPClause.h" 22 #include "clang/AST/Stmt.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Basic/PrettyStackTrace.h" 27 #include "llvm/ADT/SmallSet.h" 28 #include "llvm/BinaryFormat/Dwarf.h" 29 #include "llvm/Frontend/OpenMP/OMPConstants.h" 30 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 31 #include "llvm/IR/Constants.h" 32 #include "llvm/IR/DebugInfoMetadata.h" 33 #include "llvm/IR/Instructions.h" 34 #include "llvm/IR/IntrinsicInst.h" 35 #include "llvm/IR/Metadata.h" 36 #include "llvm/Support/AtomicOrdering.h" 37 using namespace clang; 38 using namespace CodeGen; 39 using namespace llvm::omp; 40 41 static const VarDecl *getBaseDecl(const Expr *Ref); 42 43 namespace { 44 /// Lexical scope for OpenMP executable constructs, that handles correct codegen 45 /// for captured expressions. 46 class OMPLexicalScope : public CodeGenFunction::LexicalScope { 47 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 48 for (const auto *C : S.clauses()) { 49 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 50 if (const auto *PreInit = 51 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 52 for (const auto *I : PreInit->decls()) { 53 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 54 CGF.EmitVarDecl(cast<VarDecl>(*I)); 55 } else { 56 CodeGenFunction::AutoVarEmission Emission = 57 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 58 CGF.EmitAutoVarCleanups(Emission); 59 } 60 } 61 } 62 } 63 } 64 } 65 CodeGenFunction::OMPPrivateScope InlinedShareds; 66 67 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 68 return CGF.LambdaCaptureFields.lookup(VD) || 69 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 70 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) && 71 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD)); 72 } 73 74 public: 75 OMPLexicalScope( 76 CodeGenFunction &CGF, const OMPExecutableDirective &S, 77 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None, 78 const bool EmitPreInitStmt = true) 79 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 80 InlinedShareds(CGF) { 81 if (EmitPreInitStmt) 82 emitPreInitStmt(CGF, S); 83 if (!CapturedRegion.hasValue()) 84 return; 85 assert(S.hasAssociatedStmt() && 86 "Expected associated statement for inlined directive."); 87 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion); 88 for (const auto &C : CS->captures()) { 89 if (C.capturesVariable() || C.capturesVariableByCopy()) { 90 auto *VD = C.getCapturedVar(); 91 assert(VD == VD->getCanonicalDecl() && 92 "Canonical decl must be captured."); 93 DeclRefExpr DRE( 94 CGF.getContext(), const_cast<VarDecl *>(VD), 95 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo && 96 InlinedShareds.isGlobalVarCaptured(VD)), 97 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation()); 98 InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress(CGF)); 99 } 100 } 101 (void)InlinedShareds.Privatize(); 102 } 103 }; 104 105 /// Lexical scope for OpenMP parallel construct, that handles correct codegen 106 /// for captured expressions. 107 class OMPParallelScope final : public OMPLexicalScope { 108 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 109 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 110 return !(isOpenMPTargetExecutionDirective(Kind) || 111 isOpenMPLoopBoundSharingDirective(Kind)) && 112 isOpenMPParallelDirective(Kind); 113 } 114 115 public: 116 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 117 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 118 EmitPreInitStmt(S)) {} 119 }; 120 121 /// Lexical scope for OpenMP teams construct, that handles correct codegen 122 /// for captured expressions. 123 class OMPTeamsScope final : public OMPLexicalScope { 124 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 125 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 126 return !isOpenMPTargetExecutionDirective(Kind) && 127 isOpenMPTeamsDirective(Kind); 128 } 129 130 public: 131 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 132 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 133 EmitPreInitStmt(S)) {} 134 }; 135 136 /// Private scope for OpenMP loop-based directives, that supports capturing 137 /// of used expression from loop statement. 138 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope { 139 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) { 140 const DeclStmt *PreInits; 141 CodeGenFunction::OMPMapVars PreCondVars; 142 if (auto *LD = dyn_cast<OMPLoopDirective>(&S)) { 143 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 144 for (const auto *E : LD->counters()) { 145 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 146 EmittedAsPrivate.insert(VD->getCanonicalDecl()); 147 (void)PreCondVars.setVarAddr( 148 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType())); 149 } 150 // Mark private vars as undefs. 151 for (const auto *C : LD->getClausesOfKind<OMPPrivateClause>()) { 152 for (const Expr *IRef : C->varlists()) { 153 const auto *OrigVD = 154 cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 155 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 156 QualType OrigVDTy = OrigVD->getType().getNonReferenceType(); 157 (void)PreCondVars.setVarAddr( 158 CGF, OrigVD, 159 Address(llvm::UndefValue::get(CGF.ConvertTypeForMem( 160 CGF.getContext().getPointerType(OrigVDTy))), 161 CGF.ConvertTypeForMem(OrigVDTy), 162 CGF.getContext().getDeclAlign(OrigVD))); 163 } 164 } 165 } 166 (void)PreCondVars.apply(CGF); 167 // Emit init, __range and __end variables for C++ range loops. 168 (void)OMPLoopBasedDirective::doForAllLoops( 169 LD->getInnermostCapturedStmt()->getCapturedStmt(), 170 /*TryImperfectlyNestedLoops=*/true, LD->getLoopsNumber(), 171 [&CGF](unsigned Cnt, const Stmt *CurStmt) { 172 if (const auto *CXXFor = dyn_cast<CXXForRangeStmt>(CurStmt)) { 173 if (const Stmt *Init = CXXFor->getInit()) 174 CGF.EmitStmt(Init); 175 CGF.EmitStmt(CXXFor->getRangeStmt()); 176 CGF.EmitStmt(CXXFor->getEndStmt()); 177 } 178 return false; 179 }); 180 PreInits = cast_or_null<DeclStmt>(LD->getPreInits()); 181 } else if (const auto *Tile = dyn_cast<OMPTileDirective>(&S)) { 182 PreInits = cast_or_null<DeclStmt>(Tile->getPreInits()); 183 } else if (const auto *Unroll = dyn_cast<OMPUnrollDirective>(&S)) { 184 PreInits = cast_or_null<DeclStmt>(Unroll->getPreInits()); 185 } else { 186 llvm_unreachable("Unknown loop-based directive kind."); 187 } 188 if (PreInits) { 189 for (const auto *I : PreInits->decls()) 190 CGF.EmitVarDecl(cast<VarDecl>(*I)); 191 } 192 PreCondVars.restore(CGF); 193 } 194 195 public: 196 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopBasedDirective &S) 197 : CodeGenFunction::RunCleanupsScope(CGF) { 198 emitPreInitStmt(CGF, S); 199 } 200 }; 201 202 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope { 203 CodeGenFunction::OMPPrivateScope InlinedShareds; 204 205 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 206 return CGF.LambdaCaptureFields.lookup(VD) || 207 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 208 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) && 209 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD)); 210 } 211 212 public: 213 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 214 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 215 InlinedShareds(CGF) { 216 for (const auto *C : S.clauses()) { 217 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 218 if (const auto *PreInit = 219 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 220 for (const auto *I : PreInit->decls()) { 221 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 222 CGF.EmitVarDecl(cast<VarDecl>(*I)); 223 } else { 224 CodeGenFunction::AutoVarEmission Emission = 225 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 226 CGF.EmitAutoVarCleanups(Emission); 227 } 228 } 229 } 230 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) { 231 for (const Expr *E : UDP->varlists()) { 232 const Decl *D = cast<DeclRefExpr>(E)->getDecl(); 233 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D)) 234 CGF.EmitVarDecl(*OED); 235 } 236 } else if (const auto *UDP = dyn_cast<OMPUseDeviceAddrClause>(C)) { 237 for (const Expr *E : UDP->varlists()) { 238 const Decl *D = getBaseDecl(E); 239 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D)) 240 CGF.EmitVarDecl(*OED); 241 } 242 } 243 } 244 if (!isOpenMPSimdDirective(S.getDirectiveKind())) 245 CGF.EmitOMPPrivateClause(S, InlinedShareds); 246 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) { 247 if (const Expr *E = TG->getReductionRef()) 248 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())); 249 } 250 // Temp copy arrays for inscan reductions should not be emitted as they are 251 // not used in simd only mode. 252 llvm::DenseSet<CanonicalDeclPtr<const Decl>> CopyArrayTemps; 253 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 254 if (C->getModifier() != OMPC_REDUCTION_inscan) 255 continue; 256 for (const Expr *E : C->copy_array_temps()) 257 CopyArrayTemps.insert(cast<DeclRefExpr>(E)->getDecl()); 258 } 259 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt()); 260 while (CS) { 261 for (auto &C : CS->captures()) { 262 if (C.capturesVariable() || C.capturesVariableByCopy()) { 263 auto *VD = C.getCapturedVar(); 264 if (CopyArrayTemps.contains(VD)) 265 continue; 266 assert(VD == VD->getCanonicalDecl() && 267 "Canonical decl must be captured."); 268 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD), 269 isCapturedVar(CGF, VD) || 270 (CGF.CapturedStmtInfo && 271 InlinedShareds.isGlobalVarCaptured(VD)), 272 VD->getType().getNonReferenceType(), VK_LValue, 273 C.getLocation()); 274 InlinedShareds.addPrivate(VD, CGF.EmitLValue(&DRE).getAddress(CGF)); 275 } 276 } 277 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt()); 278 } 279 (void)InlinedShareds.Privatize(); 280 } 281 }; 282 283 } // namespace 284 285 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 286 const OMPExecutableDirective &S, 287 const RegionCodeGenTy &CodeGen); 288 289 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) { 290 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) { 291 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) { 292 OrigVD = OrigVD->getCanonicalDecl(); 293 bool IsCaptured = 294 LambdaCaptureFields.lookup(OrigVD) || 295 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) || 296 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)); 297 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured, 298 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc()); 299 return EmitLValue(&DRE); 300 } 301 } 302 return EmitLValue(E); 303 } 304 305 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) { 306 ASTContext &C = getContext(); 307 llvm::Value *Size = nullptr; 308 auto SizeInChars = C.getTypeSizeInChars(Ty); 309 if (SizeInChars.isZero()) { 310 // getTypeSizeInChars() returns 0 for a VLA. 311 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) { 312 VlaSizePair VlaSize = getVLASize(VAT); 313 Ty = VlaSize.Type; 314 Size = 315 Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) : VlaSize.NumElts; 316 } 317 SizeInChars = C.getTypeSizeInChars(Ty); 318 if (SizeInChars.isZero()) 319 return llvm::ConstantInt::get(SizeTy, /*V=*/0); 320 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars)); 321 } 322 return CGM.getSize(SizeInChars); 323 } 324 325 void CodeGenFunction::GenerateOpenMPCapturedVars( 326 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) { 327 const RecordDecl *RD = S.getCapturedRecordDecl(); 328 auto CurField = RD->field_begin(); 329 auto CurCap = S.captures().begin(); 330 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 331 E = S.capture_init_end(); 332 I != E; ++I, ++CurField, ++CurCap) { 333 if (CurField->hasCapturedVLAType()) { 334 const VariableArrayType *VAT = CurField->getCapturedVLAType(); 335 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()]; 336 CapturedVars.push_back(Val); 337 } else if (CurCap->capturesThis()) { 338 CapturedVars.push_back(CXXThisValue); 339 } else if (CurCap->capturesVariableByCopy()) { 340 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation()); 341 342 // If the field is not a pointer, we need to save the actual value 343 // and load it as a void pointer. 344 if (!CurField->getType()->isAnyPointerType()) { 345 ASTContext &Ctx = getContext(); 346 Address DstAddr = CreateMemTemp( 347 Ctx.getUIntPtrType(), 348 Twine(CurCap->getCapturedVar()->getName(), ".casted")); 349 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType()); 350 351 llvm::Value *SrcAddrVal = EmitScalarConversion( 352 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()), 353 Ctx.getPointerType(CurField->getType()), CurCap->getLocation()); 354 LValue SrcLV = 355 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType()); 356 357 // Store the value using the source type pointer. 358 EmitStoreThroughLValue(RValue::get(CV), SrcLV); 359 360 // Load the value using the destination type pointer. 361 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation()); 362 } 363 CapturedVars.push_back(CV); 364 } else { 365 assert(CurCap->capturesVariable() && "Expected capture by reference."); 366 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer()); 367 } 368 } 369 } 370 371 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc, 372 QualType DstType, StringRef Name, 373 LValue AddrLV) { 374 ASTContext &Ctx = CGF.getContext(); 375 376 llvm::Value *CastedPtr = CGF.EmitScalarConversion( 377 AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(), 378 Ctx.getPointerType(DstType), Loc); 379 Address TmpAddr = 380 CGF.MakeNaturalAlignAddrLValue(CastedPtr, DstType).getAddress(CGF); 381 return TmpAddr; 382 } 383 384 static QualType getCanonicalParamType(ASTContext &C, QualType T) { 385 if (T->isLValueReferenceType()) 386 return C.getLValueReferenceType( 387 getCanonicalParamType(C, T.getNonReferenceType()), 388 /*SpelledAsLValue=*/false); 389 if (T->isPointerType()) 390 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType())); 391 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) { 392 if (const auto *VLA = dyn_cast<VariableArrayType>(A)) 393 return getCanonicalParamType(C, VLA->getElementType()); 394 if (!A->isVariablyModifiedType()) 395 return C.getCanonicalType(T); 396 } 397 return C.getCanonicalParamType(T); 398 } 399 400 namespace { 401 /// Contains required data for proper outlined function codegen. 402 struct FunctionOptions { 403 /// Captured statement for which the function is generated. 404 const CapturedStmt *S = nullptr; 405 /// true if cast to/from UIntPtr is required for variables captured by 406 /// value. 407 const bool UIntPtrCastRequired = true; 408 /// true if only casted arguments must be registered as local args or VLA 409 /// sizes. 410 const bool RegisterCastedArgsOnly = false; 411 /// Name of the generated function. 412 const StringRef FunctionName; 413 /// Location of the non-debug version of the outlined function. 414 SourceLocation Loc; 415 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired, 416 bool RegisterCastedArgsOnly, StringRef FunctionName, 417 SourceLocation Loc) 418 : S(S), UIntPtrCastRequired(UIntPtrCastRequired), 419 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly), 420 FunctionName(FunctionName), Loc(Loc) {} 421 }; 422 } // namespace 423 424 static llvm::Function *emitOutlinedFunctionPrologue( 425 CodeGenFunction &CGF, FunctionArgList &Args, 426 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> 427 &LocalAddrs, 428 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> 429 &VLASizes, 430 llvm::Value *&CXXThisValue, const FunctionOptions &FO) { 431 const CapturedDecl *CD = FO.S->getCapturedDecl(); 432 const RecordDecl *RD = FO.S->getCapturedRecordDecl(); 433 assert(CD->hasBody() && "missing CapturedDecl body"); 434 435 CXXThisValue = nullptr; 436 // Build the argument list. 437 CodeGenModule &CGM = CGF.CGM; 438 ASTContext &Ctx = CGM.getContext(); 439 FunctionArgList TargetArgs; 440 Args.append(CD->param_begin(), 441 std::next(CD->param_begin(), CD->getContextParamPosition())); 442 TargetArgs.append( 443 CD->param_begin(), 444 std::next(CD->param_begin(), CD->getContextParamPosition())); 445 auto I = FO.S->captures().begin(); 446 FunctionDecl *DebugFunctionDecl = nullptr; 447 if (!FO.UIntPtrCastRequired) { 448 FunctionProtoType::ExtProtoInfo EPI; 449 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI); 450 DebugFunctionDecl = FunctionDecl::Create( 451 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(), 452 SourceLocation(), DeclarationName(), FunctionTy, 453 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static, 454 /*UsesFPIntrin=*/false, /*isInlineSpecified=*/false, 455 /*hasWrittenPrototype=*/false); 456 } 457 for (const FieldDecl *FD : RD->fields()) { 458 QualType ArgType = FD->getType(); 459 IdentifierInfo *II = nullptr; 460 VarDecl *CapVar = nullptr; 461 462 // If this is a capture by copy and the type is not a pointer, the outlined 463 // function argument type should be uintptr and the value properly casted to 464 // uintptr. This is necessary given that the runtime library is only able to 465 // deal with pointers. We can pass in the same way the VLA type sizes to the 466 // outlined function. 467 if (FO.UIntPtrCastRequired && 468 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) || 469 I->capturesVariableArrayType())) 470 ArgType = Ctx.getUIntPtrType(); 471 472 if (I->capturesVariable() || I->capturesVariableByCopy()) { 473 CapVar = I->getCapturedVar(); 474 II = CapVar->getIdentifier(); 475 } else if (I->capturesThis()) { 476 II = &Ctx.Idents.get("this"); 477 } else { 478 assert(I->capturesVariableArrayType()); 479 II = &Ctx.Idents.get("vla"); 480 } 481 if (ArgType->isVariablyModifiedType()) 482 ArgType = getCanonicalParamType(Ctx, ArgType); 483 VarDecl *Arg; 484 if (CapVar && (CapVar->getTLSKind() != clang::VarDecl::TLS_None)) { 485 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), 486 II, ArgType, 487 ImplicitParamDecl::ThreadPrivateVar); 488 } else if (DebugFunctionDecl && (CapVar || I->capturesThis())) { 489 Arg = ParmVarDecl::Create( 490 Ctx, DebugFunctionDecl, 491 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(), 492 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType, 493 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr); 494 } else { 495 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), 496 II, ArgType, ImplicitParamDecl::Other); 497 } 498 Args.emplace_back(Arg); 499 // Do not cast arguments if we emit function with non-original types. 500 TargetArgs.emplace_back( 501 FO.UIntPtrCastRequired 502 ? Arg 503 : CGM.getOpenMPRuntime().translateParameter(FD, Arg)); 504 ++I; 505 } 506 Args.append(std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 507 CD->param_end()); 508 TargetArgs.append( 509 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 510 CD->param_end()); 511 512 // Create the function declaration. 513 const CGFunctionInfo &FuncInfo = 514 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs); 515 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 516 517 auto *F = 518 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 519 FO.FunctionName, &CGM.getModule()); 520 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 521 if (CD->isNothrow()) 522 F->setDoesNotThrow(); 523 F->setDoesNotRecurse(); 524 525 // Always inline the outlined function if optimizations are enabled. 526 if (CGM.getCodeGenOpts().OptimizationLevel != 0) { 527 F->removeFnAttr(llvm::Attribute::NoInline); 528 F->addFnAttr(llvm::Attribute::AlwaysInline); 529 } 530 531 // Generate the function. 532 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs, 533 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(), 534 FO.UIntPtrCastRequired ? FO.Loc 535 : CD->getBody()->getBeginLoc()); 536 unsigned Cnt = CD->getContextParamPosition(); 537 I = FO.S->captures().begin(); 538 for (const FieldDecl *FD : RD->fields()) { 539 // Do not map arguments if we emit function with non-original types. 540 Address LocalAddr(Address::invalid()); 541 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) { 542 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt], 543 TargetArgs[Cnt]); 544 } else { 545 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]); 546 } 547 // If we are capturing a pointer by copy we don't need to do anything, just 548 // use the value that we get from the arguments. 549 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) { 550 const VarDecl *CurVD = I->getCapturedVar(); 551 if (!FO.RegisterCastedArgsOnly) 552 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}}); 553 ++Cnt; 554 ++I; 555 continue; 556 } 557 558 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(), 559 AlignmentSource::Decl); 560 if (FD->hasCapturedVLAType()) { 561 if (FO.UIntPtrCastRequired) { 562 ArgLVal = CGF.MakeAddrLValue( 563 castValueFromUintptr(CGF, I->getLocation(), FD->getType(), 564 Args[Cnt]->getName(), ArgLVal), 565 FD->getType(), AlignmentSource::Decl); 566 } 567 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 568 const VariableArrayType *VAT = FD->getCapturedVLAType(); 569 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg); 570 } else if (I->capturesVariable()) { 571 const VarDecl *Var = I->getCapturedVar(); 572 QualType VarTy = Var->getType(); 573 Address ArgAddr = ArgLVal.getAddress(CGF); 574 if (ArgLVal.getType()->isLValueReferenceType()) { 575 ArgAddr = CGF.EmitLoadOfReference(ArgLVal); 576 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) { 577 assert(ArgLVal.getType()->isPointerType()); 578 ArgAddr = CGF.EmitLoadOfPointer( 579 ArgAddr, ArgLVal.getType()->castAs<PointerType>()); 580 } 581 if (!FO.RegisterCastedArgsOnly) { 582 LocalAddrs.insert( 583 {Args[Cnt], {Var, ArgAddr.withAlignment(Ctx.getDeclAlign(Var))}}); 584 } 585 } else if (I->capturesVariableByCopy()) { 586 assert(!FD->getType()->isAnyPointerType() && 587 "Not expecting a captured pointer."); 588 const VarDecl *Var = I->getCapturedVar(); 589 LocalAddrs.insert({Args[Cnt], 590 {Var, FO.UIntPtrCastRequired 591 ? castValueFromUintptr( 592 CGF, I->getLocation(), FD->getType(), 593 Args[Cnt]->getName(), ArgLVal) 594 : ArgLVal.getAddress(CGF)}}); 595 } else { 596 // If 'this' is captured, load it into CXXThisValue. 597 assert(I->capturesThis()); 598 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 599 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}}); 600 } 601 ++Cnt; 602 ++I; 603 } 604 605 return F; 606 } 607 608 llvm::Function * 609 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 610 SourceLocation Loc) { 611 assert( 612 CapturedStmtInfo && 613 "CapturedStmtInfo should be set when generating the captured function"); 614 const CapturedDecl *CD = S.getCapturedDecl(); 615 // Build the argument list. 616 bool NeedWrapperFunction = 617 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo(); 618 FunctionArgList Args; 619 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs; 620 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes; 621 SmallString<256> Buffer; 622 llvm::raw_svector_ostream Out(Buffer); 623 Out << CapturedStmtInfo->getHelperName(); 624 if (NeedWrapperFunction) 625 Out << "_debug__"; 626 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false, 627 Out.str(), Loc); 628 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs, 629 VLASizes, CXXThisValue, FO); 630 CodeGenFunction::OMPPrivateScope LocalScope(*this); 631 for (const auto &LocalAddrPair : LocalAddrs) { 632 if (LocalAddrPair.second.first) { 633 LocalScope.addPrivate(LocalAddrPair.second.first, 634 LocalAddrPair.second.second); 635 } 636 } 637 (void)LocalScope.Privatize(); 638 for (const auto &VLASizePair : VLASizes) 639 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second; 640 PGO.assignRegionCounters(GlobalDecl(CD), F); 641 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 642 (void)LocalScope.ForceCleanup(); 643 FinishFunction(CD->getBodyRBrace()); 644 if (!NeedWrapperFunction) 645 return F; 646 647 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true, 648 /*RegisterCastedArgsOnly=*/true, 649 CapturedStmtInfo->getHelperName(), Loc); 650 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true); 651 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo; 652 Args.clear(); 653 LocalAddrs.clear(); 654 VLASizes.clear(); 655 llvm::Function *WrapperF = 656 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes, 657 WrapperCGF.CXXThisValue, WrapperFO); 658 llvm::SmallVector<llvm::Value *, 4> CallArgs; 659 auto *PI = F->arg_begin(); 660 for (const auto *Arg : Args) { 661 llvm::Value *CallArg; 662 auto I = LocalAddrs.find(Arg); 663 if (I != LocalAddrs.end()) { 664 LValue LV = WrapperCGF.MakeAddrLValue( 665 I->second.second, 666 I->second.first ? I->second.first->getType() : Arg->getType(), 667 AlignmentSource::Decl); 668 if (LV.getType()->isAnyComplexType()) 669 LV.setAddress(WrapperCGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 670 LV.getAddress(WrapperCGF), 671 PI->getType()->getPointerTo( 672 LV.getAddress(WrapperCGF).getAddressSpace()), 673 PI->getType())); 674 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 675 } else { 676 auto EI = VLASizes.find(Arg); 677 if (EI != VLASizes.end()) { 678 CallArg = EI->second.second; 679 } else { 680 LValue LV = 681 WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg), 682 Arg->getType(), AlignmentSource::Decl); 683 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 684 } 685 } 686 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType())); 687 ++PI; 688 } 689 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs); 690 WrapperCGF.FinishFunction(); 691 return WrapperF; 692 } 693 694 //===----------------------------------------------------------------------===// 695 // OpenMP Directive Emission 696 //===----------------------------------------------------------------------===// 697 void CodeGenFunction::EmitOMPAggregateAssign( 698 Address DestAddr, Address SrcAddr, QualType OriginalType, 699 const llvm::function_ref<void(Address, Address)> CopyGen) { 700 // Perform element-by-element initialization. 701 QualType ElementTy; 702 703 // Drill down to the base element type on both arrays. 704 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe(); 705 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr); 706 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 707 708 llvm::Value *SrcBegin = SrcAddr.getPointer(); 709 llvm::Value *DestBegin = DestAddr.getPointer(); 710 // Cast from pointer to array type to pointer to single element. 711 llvm::Value *DestEnd = 712 Builder.CreateGEP(DestAddr.getElementType(), DestBegin, NumElements); 713 // The basic structure here is a while-do loop. 714 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body"); 715 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done"); 716 llvm::Value *IsEmpty = 717 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty"); 718 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 719 720 // Enter the loop body, making that address the current address. 721 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 722 EmitBlock(BodyBB); 723 724 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy); 725 726 llvm::PHINode *SrcElementPHI = 727 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 728 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 729 Address SrcElementCurrent = 730 Address(SrcElementPHI, SrcAddr.getElementType(), 731 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 732 733 llvm::PHINode *DestElementPHI = Builder.CreatePHI( 734 DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 735 DestElementPHI->addIncoming(DestBegin, EntryBB); 736 Address DestElementCurrent = 737 Address(DestElementPHI, DestAddr.getElementType(), 738 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 739 740 // Emit copy. 741 CopyGen(DestElementCurrent, SrcElementCurrent); 742 743 // Shift the address forward by one element. 744 llvm::Value *DestElementNext = 745 Builder.CreateConstGEP1_32(DestAddr.getElementType(), DestElementPHI, 746 /*Idx0=*/1, "omp.arraycpy.dest.element"); 747 llvm::Value *SrcElementNext = 748 Builder.CreateConstGEP1_32(SrcAddr.getElementType(), SrcElementPHI, 749 /*Idx0=*/1, "omp.arraycpy.src.element"); 750 // Check whether we've reached the end. 751 llvm::Value *Done = 752 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 753 Builder.CreateCondBr(Done, DoneBB, BodyBB); 754 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock()); 755 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock()); 756 757 // Done. 758 EmitBlock(DoneBB, /*IsFinished=*/true); 759 } 760 761 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr, 762 Address SrcAddr, const VarDecl *DestVD, 763 const VarDecl *SrcVD, const Expr *Copy) { 764 if (OriginalType->isArrayType()) { 765 const auto *BO = dyn_cast<BinaryOperator>(Copy); 766 if (BO && BO->getOpcode() == BO_Assign) { 767 // Perform simple memcpy for simple copying. 768 LValue Dest = MakeAddrLValue(DestAddr, OriginalType); 769 LValue Src = MakeAddrLValue(SrcAddr, OriginalType); 770 EmitAggregateAssign(Dest, Src, OriginalType); 771 } else { 772 // For arrays with complex element types perform element by element 773 // copying. 774 EmitOMPAggregateAssign( 775 DestAddr, SrcAddr, OriginalType, 776 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) { 777 // Working with the single array element, so have to remap 778 // destination and source variables to corresponding array 779 // elements. 780 CodeGenFunction::OMPPrivateScope Remap(*this); 781 Remap.addPrivate(DestVD, DestElement); 782 Remap.addPrivate(SrcVD, SrcElement); 783 (void)Remap.Privatize(); 784 EmitIgnoredExpr(Copy); 785 }); 786 } 787 } else { 788 // Remap pseudo source variable to private copy. 789 CodeGenFunction::OMPPrivateScope Remap(*this); 790 Remap.addPrivate(SrcVD, SrcAddr); 791 Remap.addPrivate(DestVD, DestAddr); 792 (void)Remap.Privatize(); 793 // Emit copying of the whole variable. 794 EmitIgnoredExpr(Copy); 795 } 796 } 797 798 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 799 OMPPrivateScope &PrivateScope) { 800 if (!HaveInsertPoint()) 801 return false; 802 bool DeviceConstTarget = 803 getLangOpts().OpenMPIsDevice && 804 isOpenMPTargetExecutionDirective(D.getDirectiveKind()); 805 bool FirstprivateIsLastprivate = false; 806 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates; 807 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 808 for (const auto *D : C->varlists()) 809 Lastprivates.try_emplace( 810 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(), 811 C->getKind()); 812 } 813 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate; 814 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 815 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind()); 816 // Force emission of the firstprivate copy if the directive does not emit 817 // outlined function, like omp for, omp simd, omp distribute etc. 818 bool MustEmitFirstprivateCopy = 819 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown; 820 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 821 const auto *IRef = C->varlist_begin(); 822 const auto *InitsRef = C->inits().begin(); 823 for (const Expr *IInit : C->private_copies()) { 824 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 825 bool ThisFirstprivateIsLastprivate = 826 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0; 827 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD); 828 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 829 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD && 830 !FD->getType()->isReferenceType() && 831 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 832 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()); 833 ++IRef; 834 ++InitsRef; 835 continue; 836 } 837 // Do not emit copy for firstprivate constant variables in target regions, 838 // captured by reference. 839 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) && 840 FD && FD->getType()->isReferenceType() && 841 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 842 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()); 843 ++IRef; 844 ++InitsRef; 845 continue; 846 } 847 FirstprivateIsLastprivate = 848 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate; 849 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) { 850 const auto *VDInit = 851 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl()); 852 bool IsRegistered; 853 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 854 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr, 855 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 856 LValue OriginalLVal; 857 if (!FD) { 858 // Check if the firstprivate variable is just a constant value. 859 ConstantEmission CE = tryEmitAsConstant(&DRE); 860 if (CE && !CE.isReference()) { 861 // Constant value, no need to create a copy. 862 ++IRef; 863 ++InitsRef; 864 continue; 865 } 866 if (CE && CE.isReference()) { 867 OriginalLVal = CE.getReferenceLValue(*this, &DRE); 868 } else { 869 assert(!CE && "Expected non-constant firstprivate."); 870 OriginalLVal = EmitLValue(&DRE); 871 } 872 } else { 873 OriginalLVal = EmitLValue(&DRE); 874 } 875 QualType Type = VD->getType(); 876 if (Type->isArrayType()) { 877 // Emit VarDecl with copy init for arrays. 878 // Get the address of the original variable captured in current 879 // captured region. 880 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 881 const Expr *Init = VD->getInit(); 882 if (!isa<CXXConstructExpr>(Init) || isTrivialInitializer(Init)) { 883 // Perform simple memcpy. 884 LValue Dest = MakeAddrLValue(Emission.getAllocatedAddress(), Type); 885 EmitAggregateAssign(Dest, OriginalLVal, Type); 886 } else { 887 EmitOMPAggregateAssign( 888 Emission.getAllocatedAddress(), OriginalLVal.getAddress(*this), 889 Type, 890 [this, VDInit, Init](Address DestElement, Address SrcElement) { 891 // Clean up any temporaries needed by the 892 // initialization. 893 RunCleanupsScope InitScope(*this); 894 // Emit initialization for single element. 895 setAddrOfLocalVar(VDInit, SrcElement); 896 EmitAnyExprToMem(Init, DestElement, 897 Init->getType().getQualifiers(), 898 /*IsInitializer*/ false); 899 LocalDeclMap.erase(VDInit); 900 }); 901 } 902 EmitAutoVarCleanups(Emission); 903 IsRegistered = 904 PrivateScope.addPrivate(OrigVD, Emission.getAllocatedAddress()); 905 } else { 906 Address OriginalAddr = OriginalLVal.getAddress(*this); 907 // Emit private VarDecl with copy init. 908 // Remap temp VDInit variable to the address of the original 909 // variable (for proper handling of captured global variables). 910 setAddrOfLocalVar(VDInit, OriginalAddr); 911 EmitDecl(*VD); 912 LocalDeclMap.erase(VDInit); 913 Address VDAddr = GetAddrOfLocalVar(VD); 914 if (ThisFirstprivateIsLastprivate && 915 Lastprivates[OrigVD->getCanonicalDecl()] == 916 OMPC_LASTPRIVATE_conditional) { 917 // Create/init special variable for lastprivate conditionals. 918 llvm::Value *V = 919 EmitLoadOfScalar(MakeAddrLValue(VDAddr, (*IRef)->getType(), 920 AlignmentSource::Decl), 921 (*IRef)->getExprLoc()); 922 VDAddr = CGM.getOpenMPRuntime().emitLastprivateConditionalInit( 923 *this, OrigVD); 924 EmitStoreOfScalar(V, MakeAddrLValue(VDAddr, (*IRef)->getType(), 925 AlignmentSource::Decl)); 926 LocalDeclMap.erase(VD); 927 setAddrOfLocalVar(VD, VDAddr); 928 } 929 IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr); 930 } 931 assert(IsRegistered && 932 "firstprivate var already registered as private"); 933 // Silence the warning about unused variable. 934 (void)IsRegistered; 935 } 936 ++IRef; 937 ++InitsRef; 938 } 939 } 940 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty(); 941 } 942 943 void CodeGenFunction::EmitOMPPrivateClause( 944 const OMPExecutableDirective &D, 945 CodeGenFunction::OMPPrivateScope &PrivateScope) { 946 if (!HaveInsertPoint()) 947 return; 948 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 949 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) { 950 auto IRef = C->varlist_begin(); 951 for (const Expr *IInit : C->private_copies()) { 952 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 953 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 954 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 955 EmitDecl(*VD); 956 // Emit private VarDecl with copy init. 957 bool IsRegistered = 958 PrivateScope.addPrivate(OrigVD, GetAddrOfLocalVar(VD)); 959 assert(IsRegistered && "private var already registered as private"); 960 // Silence the warning about unused variable. 961 (void)IsRegistered; 962 } 963 ++IRef; 964 } 965 } 966 } 967 968 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) { 969 if (!HaveInsertPoint()) 970 return false; 971 // threadprivate_var1 = master_threadprivate_var1; 972 // operator=(threadprivate_var2, master_threadprivate_var2); 973 // ... 974 // __kmpc_barrier(&loc, global_tid); 975 llvm::DenseSet<const VarDecl *> CopiedVars; 976 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr; 977 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) { 978 auto IRef = C->varlist_begin(); 979 auto ISrcRef = C->source_exprs().begin(); 980 auto IDestRef = C->destination_exprs().begin(); 981 for (const Expr *AssignOp : C->assignment_ops()) { 982 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 983 QualType Type = VD->getType(); 984 if (CopiedVars.insert(VD->getCanonicalDecl()).second) { 985 // Get the address of the master variable. If we are emitting code with 986 // TLS support, the address is passed from the master as field in the 987 // captured declaration. 988 Address MasterAddr = Address::invalid(); 989 if (getLangOpts().OpenMPUseTLS && 990 getContext().getTargetInfo().isTLSSupported()) { 991 assert(CapturedStmtInfo->lookup(VD) && 992 "Copyin threadprivates should have been captured!"); 993 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true, 994 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 995 MasterAddr = EmitLValue(&DRE).getAddress(*this); 996 LocalDeclMap.erase(VD); 997 } else { 998 MasterAddr = 999 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD) 1000 : CGM.GetAddrOfGlobal(VD), 1001 CGM.getTypes().ConvertTypeForMem(VD->getType()), 1002 getContext().getDeclAlign(VD)); 1003 } 1004 // Get the address of the threadprivate variable. 1005 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this); 1006 if (CopiedVars.size() == 1) { 1007 // At first check if current thread is a master thread. If it is, no 1008 // need to copy data. 1009 CopyBegin = createBasicBlock("copyin.not.master"); 1010 CopyEnd = createBasicBlock("copyin.not.master.end"); 1011 // TODO: Avoid ptrtoint conversion. 1012 auto *MasterAddrInt = 1013 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy); 1014 auto *PrivateAddrInt = 1015 Builder.CreatePtrToInt(PrivateAddr.getPointer(), CGM.IntPtrTy); 1016 Builder.CreateCondBr( 1017 Builder.CreateICmpNE(MasterAddrInt, PrivateAddrInt), CopyBegin, 1018 CopyEnd); 1019 EmitBlock(CopyBegin); 1020 } 1021 const auto *SrcVD = 1022 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 1023 const auto *DestVD = 1024 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1025 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp); 1026 } 1027 ++IRef; 1028 ++ISrcRef; 1029 ++IDestRef; 1030 } 1031 } 1032 if (CopyEnd) { 1033 // Exit out of copying procedure for non-master thread. 1034 EmitBlock(CopyEnd, /*IsFinished=*/true); 1035 return true; 1036 } 1037 return false; 1038 } 1039 1040 bool CodeGenFunction::EmitOMPLastprivateClauseInit( 1041 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) { 1042 if (!HaveInsertPoint()) 1043 return false; 1044 bool HasAtLeastOneLastprivate = false; 1045 llvm::DenseSet<const VarDecl *> SIMDLCVs; 1046 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 1047 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 1048 for (const Expr *C : LoopDirective->counters()) { 1049 SIMDLCVs.insert( 1050 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 1051 } 1052 } 1053 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1054 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1055 HasAtLeastOneLastprivate = true; 1056 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && 1057 !getLangOpts().OpenMPSimd) 1058 break; 1059 const auto *IRef = C->varlist_begin(); 1060 const auto *IDestRef = C->destination_exprs().begin(); 1061 for (const Expr *IInit : C->private_copies()) { 1062 // Keep the address of the original variable for future update at the end 1063 // of the loop. 1064 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1065 // Taskloops do not require additional initialization, it is done in 1066 // runtime support library. 1067 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) { 1068 const auto *DestVD = 1069 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1070 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1071 /*RefersToEnclosingVariableOrCapture=*/ 1072 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1073 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 1074 PrivateScope.addPrivate(DestVD, EmitLValue(&DRE).getAddress(*this)); 1075 // Check if the variable is also a firstprivate: in this case IInit is 1076 // not generated. Initialization of this variable will happen in codegen 1077 // for 'firstprivate' clause. 1078 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) { 1079 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 1080 Address VDAddr = Address::invalid(); 1081 if (C->getKind() == OMPC_LASTPRIVATE_conditional) { 1082 VDAddr = CGM.getOpenMPRuntime().emitLastprivateConditionalInit( 1083 *this, OrigVD); 1084 setAddrOfLocalVar(VD, VDAddr); 1085 } else { 1086 // Emit private VarDecl with copy init. 1087 EmitDecl(*VD); 1088 VDAddr = GetAddrOfLocalVar(VD); 1089 } 1090 bool IsRegistered = PrivateScope.addPrivate(OrigVD, VDAddr); 1091 assert(IsRegistered && 1092 "lastprivate var already registered as private"); 1093 (void)IsRegistered; 1094 } 1095 } 1096 ++IRef; 1097 ++IDestRef; 1098 } 1099 } 1100 return HasAtLeastOneLastprivate; 1101 } 1102 1103 void CodeGenFunction::EmitOMPLastprivateClauseFinal( 1104 const OMPExecutableDirective &D, bool NoFinals, 1105 llvm::Value *IsLastIterCond) { 1106 if (!HaveInsertPoint()) 1107 return; 1108 // Emit following code: 1109 // if (<IsLastIterCond>) { 1110 // orig_var1 = private_orig_var1; 1111 // ... 1112 // orig_varn = private_orig_varn; 1113 // } 1114 llvm::BasicBlock *ThenBB = nullptr; 1115 llvm::BasicBlock *DoneBB = nullptr; 1116 if (IsLastIterCond) { 1117 // Emit implicit barrier if at least one lastprivate conditional is found 1118 // and this is not a simd mode. 1119 if (!getLangOpts().OpenMPSimd && 1120 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(), 1121 [](const OMPLastprivateClause *C) { 1122 return C->getKind() == OMPC_LASTPRIVATE_conditional; 1123 })) { 1124 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(), 1125 OMPD_unknown, 1126 /*EmitChecks=*/false, 1127 /*ForceSimpleCall=*/true); 1128 } 1129 ThenBB = createBasicBlock(".omp.lastprivate.then"); 1130 DoneBB = createBasicBlock(".omp.lastprivate.done"); 1131 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB); 1132 EmitBlock(ThenBB); 1133 } 1134 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1135 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates; 1136 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) { 1137 auto IC = LoopDirective->counters().begin(); 1138 for (const Expr *F : LoopDirective->finals()) { 1139 const auto *D = 1140 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl(); 1141 if (NoFinals) 1142 AlreadyEmittedVars.insert(D); 1143 else 1144 LoopCountersAndUpdates[D] = F; 1145 ++IC; 1146 } 1147 } 1148 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1149 auto IRef = C->varlist_begin(); 1150 auto ISrcRef = C->source_exprs().begin(); 1151 auto IDestRef = C->destination_exprs().begin(); 1152 for (const Expr *AssignOp : C->assignment_ops()) { 1153 const auto *PrivateVD = 1154 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1155 QualType Type = PrivateVD->getType(); 1156 const auto *CanonicalVD = PrivateVD->getCanonicalDecl(); 1157 if (AlreadyEmittedVars.insert(CanonicalVD).second) { 1158 // If lastprivate variable is a loop control variable for loop-based 1159 // directive, update its value before copyin back to original 1160 // variable. 1161 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) 1162 EmitIgnoredExpr(FinalExpr); 1163 const auto *SrcVD = 1164 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 1165 const auto *DestVD = 1166 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1167 // Get the address of the private variable. 1168 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD); 1169 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>()) 1170 PrivateAddr = Address( 1171 Builder.CreateLoad(PrivateAddr), 1172 CGM.getTypes().ConvertTypeForMem(RefTy->getPointeeType()), 1173 CGM.getNaturalTypeAlignment(RefTy->getPointeeType())); 1174 // Store the last value to the private copy in the last iteration. 1175 if (C->getKind() == OMPC_LASTPRIVATE_conditional) 1176 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate( 1177 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD, 1178 (*IRef)->getExprLoc()); 1179 // Get the address of the original variable. 1180 Address OriginalAddr = GetAddrOfLocalVar(DestVD); 1181 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp); 1182 } 1183 ++IRef; 1184 ++ISrcRef; 1185 ++IDestRef; 1186 } 1187 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 1188 EmitIgnoredExpr(PostUpdate); 1189 } 1190 if (IsLastIterCond) 1191 EmitBlock(DoneBB, /*IsFinished=*/true); 1192 } 1193 1194 void CodeGenFunction::EmitOMPReductionClauseInit( 1195 const OMPExecutableDirective &D, 1196 CodeGenFunction::OMPPrivateScope &PrivateScope, bool ForInscan) { 1197 if (!HaveInsertPoint()) 1198 return; 1199 SmallVector<const Expr *, 4> Shareds; 1200 SmallVector<const Expr *, 4> Privates; 1201 SmallVector<const Expr *, 4> ReductionOps; 1202 SmallVector<const Expr *, 4> LHSs; 1203 SmallVector<const Expr *, 4> RHSs; 1204 OMPTaskDataTy Data; 1205 SmallVector<const Expr *, 4> TaskLHSs; 1206 SmallVector<const Expr *, 4> TaskRHSs; 1207 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1208 if (ForInscan != (C->getModifier() == OMPC_REDUCTION_inscan)) 1209 continue; 1210 Shareds.append(C->varlist_begin(), C->varlist_end()); 1211 Privates.append(C->privates().begin(), C->privates().end()); 1212 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1213 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1214 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1215 if (C->getModifier() == OMPC_REDUCTION_task) { 1216 Data.ReductionVars.append(C->privates().begin(), C->privates().end()); 1217 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 1218 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 1219 Data.ReductionOps.append(C->reduction_ops().begin(), 1220 C->reduction_ops().end()); 1221 TaskLHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1222 TaskRHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1223 } 1224 } 1225 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps); 1226 unsigned Count = 0; 1227 auto *ILHS = LHSs.begin(); 1228 auto *IRHS = RHSs.begin(); 1229 auto *IPriv = Privates.begin(); 1230 for (const Expr *IRef : Shareds) { 1231 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl()); 1232 // Emit private VarDecl with reduction init. 1233 RedCG.emitSharedOrigLValue(*this, Count); 1234 RedCG.emitAggregateType(*this, Count); 1235 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD); 1236 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(), 1237 RedCG.getSharedLValue(Count).getAddress(*this), 1238 [&Emission](CodeGenFunction &CGF) { 1239 CGF.EmitAutoVarInit(Emission); 1240 return true; 1241 }); 1242 EmitAutoVarCleanups(Emission); 1243 Address BaseAddr = RedCG.adjustPrivateAddress( 1244 *this, Count, Emission.getAllocatedAddress()); 1245 bool IsRegistered = 1246 PrivateScope.addPrivate(RedCG.getBaseDecl(Count), BaseAddr); 1247 assert(IsRegistered && "private var already registered as private"); 1248 // Silence the warning about unused variable. 1249 (void)IsRegistered; 1250 1251 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 1252 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 1253 QualType Type = PrivateVD->getType(); 1254 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef); 1255 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) { 1256 // Store the address of the original variable associated with the LHS 1257 // implicit variable. 1258 PrivateScope.addPrivate(LHSVD, 1259 RedCG.getSharedLValue(Count).getAddress(*this)); 1260 PrivateScope.addPrivate(RHSVD, GetAddrOfLocalVar(PrivateVD)); 1261 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) || 1262 isa<ArraySubscriptExpr>(IRef)) { 1263 // Store the address of the original variable associated with the LHS 1264 // implicit variable. 1265 PrivateScope.addPrivate(LHSVD, 1266 RedCG.getSharedLValue(Count).getAddress(*this)); 1267 PrivateScope.addPrivate(RHSVD, Builder.CreateElementBitCast( 1268 GetAddrOfLocalVar(PrivateVD), 1269 ConvertTypeForMem(RHSVD->getType()), 1270 "rhs.begin")); 1271 } else { 1272 QualType Type = PrivateVD->getType(); 1273 bool IsArray = getContext().getAsArrayType(Type) != nullptr; 1274 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this); 1275 // Store the address of the original variable associated with the LHS 1276 // implicit variable. 1277 if (IsArray) { 1278 OriginalAddr = Builder.CreateElementBitCast( 1279 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin"); 1280 } 1281 PrivateScope.addPrivate(LHSVD, OriginalAddr); 1282 PrivateScope.addPrivate( 1283 RHSVD, IsArray ? Builder.CreateElementBitCast( 1284 GetAddrOfLocalVar(PrivateVD), 1285 ConvertTypeForMem(RHSVD->getType()), "rhs.begin") 1286 : GetAddrOfLocalVar(PrivateVD)); 1287 } 1288 ++ILHS; 1289 ++IRHS; 1290 ++IPriv; 1291 ++Count; 1292 } 1293 if (!Data.ReductionVars.empty()) { 1294 Data.IsReductionWithTaskMod = true; 1295 Data.IsWorksharingReduction = 1296 isOpenMPWorksharingDirective(D.getDirectiveKind()); 1297 llvm::Value *ReductionDesc = CGM.getOpenMPRuntime().emitTaskReductionInit( 1298 *this, D.getBeginLoc(), TaskLHSs, TaskRHSs, Data); 1299 const Expr *TaskRedRef = nullptr; 1300 switch (D.getDirectiveKind()) { 1301 case OMPD_parallel: 1302 TaskRedRef = cast<OMPParallelDirective>(D).getTaskReductionRefExpr(); 1303 break; 1304 case OMPD_for: 1305 TaskRedRef = cast<OMPForDirective>(D).getTaskReductionRefExpr(); 1306 break; 1307 case OMPD_sections: 1308 TaskRedRef = cast<OMPSectionsDirective>(D).getTaskReductionRefExpr(); 1309 break; 1310 case OMPD_parallel_for: 1311 TaskRedRef = cast<OMPParallelForDirective>(D).getTaskReductionRefExpr(); 1312 break; 1313 case OMPD_parallel_master: 1314 TaskRedRef = 1315 cast<OMPParallelMasterDirective>(D).getTaskReductionRefExpr(); 1316 break; 1317 case OMPD_parallel_sections: 1318 TaskRedRef = 1319 cast<OMPParallelSectionsDirective>(D).getTaskReductionRefExpr(); 1320 break; 1321 case OMPD_target_parallel: 1322 TaskRedRef = 1323 cast<OMPTargetParallelDirective>(D).getTaskReductionRefExpr(); 1324 break; 1325 case OMPD_target_parallel_for: 1326 TaskRedRef = 1327 cast<OMPTargetParallelForDirective>(D).getTaskReductionRefExpr(); 1328 break; 1329 case OMPD_distribute_parallel_for: 1330 TaskRedRef = 1331 cast<OMPDistributeParallelForDirective>(D).getTaskReductionRefExpr(); 1332 break; 1333 case OMPD_teams_distribute_parallel_for: 1334 TaskRedRef = cast<OMPTeamsDistributeParallelForDirective>(D) 1335 .getTaskReductionRefExpr(); 1336 break; 1337 case OMPD_target_teams_distribute_parallel_for: 1338 TaskRedRef = cast<OMPTargetTeamsDistributeParallelForDirective>(D) 1339 .getTaskReductionRefExpr(); 1340 break; 1341 case OMPD_simd: 1342 case OMPD_for_simd: 1343 case OMPD_section: 1344 case OMPD_single: 1345 case OMPD_master: 1346 case OMPD_critical: 1347 case OMPD_parallel_for_simd: 1348 case OMPD_task: 1349 case OMPD_taskyield: 1350 case OMPD_barrier: 1351 case OMPD_taskwait: 1352 case OMPD_taskgroup: 1353 case OMPD_flush: 1354 case OMPD_depobj: 1355 case OMPD_scan: 1356 case OMPD_ordered: 1357 case OMPD_atomic: 1358 case OMPD_teams: 1359 case OMPD_target: 1360 case OMPD_cancellation_point: 1361 case OMPD_cancel: 1362 case OMPD_target_data: 1363 case OMPD_target_enter_data: 1364 case OMPD_target_exit_data: 1365 case OMPD_taskloop: 1366 case OMPD_taskloop_simd: 1367 case OMPD_master_taskloop: 1368 case OMPD_master_taskloop_simd: 1369 case OMPD_parallel_master_taskloop: 1370 case OMPD_parallel_master_taskloop_simd: 1371 case OMPD_distribute: 1372 case OMPD_target_update: 1373 case OMPD_distribute_parallel_for_simd: 1374 case OMPD_distribute_simd: 1375 case OMPD_target_parallel_for_simd: 1376 case OMPD_target_simd: 1377 case OMPD_teams_distribute: 1378 case OMPD_teams_distribute_simd: 1379 case OMPD_teams_distribute_parallel_for_simd: 1380 case OMPD_target_teams: 1381 case OMPD_target_teams_distribute: 1382 case OMPD_target_teams_distribute_parallel_for_simd: 1383 case OMPD_target_teams_distribute_simd: 1384 case OMPD_declare_target: 1385 case OMPD_end_declare_target: 1386 case OMPD_threadprivate: 1387 case OMPD_allocate: 1388 case OMPD_declare_reduction: 1389 case OMPD_declare_mapper: 1390 case OMPD_declare_simd: 1391 case OMPD_requires: 1392 case OMPD_declare_variant: 1393 case OMPD_begin_declare_variant: 1394 case OMPD_end_declare_variant: 1395 case OMPD_unknown: 1396 default: 1397 llvm_unreachable("Enexpected directive with task reductions."); 1398 } 1399 1400 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(TaskRedRef)->getDecl()); 1401 EmitVarDecl(*VD); 1402 EmitStoreOfScalar(ReductionDesc, GetAddrOfLocalVar(VD), 1403 /*Volatile=*/false, TaskRedRef->getType()); 1404 } 1405 } 1406 1407 void CodeGenFunction::EmitOMPReductionClauseFinal( 1408 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) { 1409 if (!HaveInsertPoint()) 1410 return; 1411 llvm::SmallVector<const Expr *, 8> Privates; 1412 llvm::SmallVector<const Expr *, 8> LHSExprs; 1413 llvm::SmallVector<const Expr *, 8> RHSExprs; 1414 llvm::SmallVector<const Expr *, 8> ReductionOps; 1415 bool HasAtLeastOneReduction = false; 1416 bool IsReductionWithTaskMod = false; 1417 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1418 // Do not emit for inscan reductions. 1419 if (C->getModifier() == OMPC_REDUCTION_inscan) 1420 continue; 1421 HasAtLeastOneReduction = true; 1422 Privates.append(C->privates().begin(), C->privates().end()); 1423 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1424 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1425 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1426 IsReductionWithTaskMod = 1427 IsReductionWithTaskMod || C->getModifier() == OMPC_REDUCTION_task; 1428 } 1429 if (HasAtLeastOneReduction) { 1430 if (IsReductionWithTaskMod) { 1431 CGM.getOpenMPRuntime().emitTaskReductionFini( 1432 *this, D.getBeginLoc(), 1433 isOpenMPWorksharingDirective(D.getDirectiveKind())); 1434 } 1435 bool WithNowait = D.getSingleClause<OMPNowaitClause>() || 1436 isOpenMPParallelDirective(D.getDirectiveKind()) || 1437 ReductionKind == OMPD_simd; 1438 bool SimpleReduction = ReductionKind == OMPD_simd; 1439 // Emit nowait reduction if nowait clause is present or directive is a 1440 // parallel directive (it always has implicit barrier). 1441 CGM.getOpenMPRuntime().emitReduction( 1442 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps, 1443 {WithNowait, SimpleReduction, ReductionKind}); 1444 } 1445 } 1446 1447 static void emitPostUpdateForReductionClause( 1448 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1449 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1450 if (!CGF.HaveInsertPoint()) 1451 return; 1452 llvm::BasicBlock *DoneBB = nullptr; 1453 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1454 if (const Expr *PostUpdate = C->getPostUpdateExpr()) { 1455 if (!DoneBB) { 1456 if (llvm::Value *Cond = CondGen(CGF)) { 1457 // If the first post-update expression is found, emit conditional 1458 // block if it was requested. 1459 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu"); 1460 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done"); 1461 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1462 CGF.EmitBlock(ThenBB); 1463 } 1464 } 1465 CGF.EmitIgnoredExpr(PostUpdate); 1466 } 1467 } 1468 if (DoneBB) 1469 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 1470 } 1471 1472 namespace { 1473 /// Codegen lambda for appending distribute lower and upper bounds to outlined 1474 /// parallel function. This is necessary for combined constructs such as 1475 /// 'distribute parallel for' 1476 typedef llvm::function_ref<void(CodeGenFunction &, 1477 const OMPExecutableDirective &, 1478 llvm::SmallVectorImpl<llvm::Value *> &)> 1479 CodeGenBoundParametersTy; 1480 } // anonymous namespace 1481 1482 static void 1483 checkForLastprivateConditionalUpdate(CodeGenFunction &CGF, 1484 const OMPExecutableDirective &S) { 1485 if (CGF.getLangOpts().OpenMP < 50) 1486 return; 1487 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls; 1488 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 1489 for (const Expr *Ref : C->varlists()) { 1490 if (!Ref->getType()->isScalarType()) 1491 continue; 1492 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1493 if (!DRE) 1494 continue; 1495 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1496 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1497 } 1498 } 1499 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 1500 for (const Expr *Ref : C->varlists()) { 1501 if (!Ref->getType()->isScalarType()) 1502 continue; 1503 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1504 if (!DRE) 1505 continue; 1506 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1507 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1508 } 1509 } 1510 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) { 1511 for (const Expr *Ref : C->varlists()) { 1512 if (!Ref->getType()->isScalarType()) 1513 continue; 1514 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1515 if (!DRE) 1516 continue; 1517 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1518 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1519 } 1520 } 1521 // Privates should ne analyzed since they are not captured at all. 1522 // Task reductions may be skipped - tasks are ignored. 1523 // Firstprivates do not return value but may be passed by reference - no need 1524 // to check for updated lastprivate conditional. 1525 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 1526 for (const Expr *Ref : C->varlists()) { 1527 if (!Ref->getType()->isScalarType()) 1528 continue; 1529 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1530 if (!DRE) 1531 continue; 1532 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1533 } 1534 } 1535 CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional( 1536 CGF, S, PrivateDecls); 1537 } 1538 1539 static void emitCommonOMPParallelDirective( 1540 CodeGenFunction &CGF, const OMPExecutableDirective &S, 1541 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1542 const CodeGenBoundParametersTy &CodeGenBoundParameters) { 1543 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1544 llvm::Value *NumThreads = nullptr; 1545 llvm::Function *OutlinedFn = 1546 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction( 1547 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 1548 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) { 1549 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 1550 NumThreads = CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 1551 /*IgnoreResultAssign=*/true); 1552 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause( 1553 CGF, NumThreads, NumThreadsClause->getBeginLoc()); 1554 } 1555 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) { 1556 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF); 1557 CGF.CGM.getOpenMPRuntime().emitProcBindClause( 1558 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc()); 1559 } 1560 const Expr *IfCond = nullptr; 1561 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 1562 if (C->getNameModifier() == OMPD_unknown || 1563 C->getNameModifier() == OMPD_parallel) { 1564 IfCond = C->getCondition(); 1565 break; 1566 } 1567 } 1568 1569 OMPParallelScope Scope(CGF, S); 1570 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 1571 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk 1572 // lower and upper bounds with the pragma 'for' chunking mechanism. 1573 // The following lambda takes care of appending the lower and upper bound 1574 // parameters when necessary 1575 CodeGenBoundParameters(CGF, S, CapturedVars); 1576 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 1577 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn, 1578 CapturedVars, IfCond, NumThreads); 1579 } 1580 1581 static bool isAllocatableDecl(const VarDecl *VD) { 1582 const VarDecl *CVD = VD->getCanonicalDecl(); 1583 if (!CVD->hasAttr<OMPAllocateDeclAttr>()) 1584 return false; 1585 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); 1586 // Use the default allocation. 1587 return !((AA->getAllocatorType() == OMPAllocateDeclAttr::OMPDefaultMemAlloc || 1588 AA->getAllocatorType() == OMPAllocateDeclAttr::OMPNullMemAlloc) && 1589 !AA->getAllocator()); 1590 } 1591 1592 static void emitEmptyBoundParameters(CodeGenFunction &, 1593 const OMPExecutableDirective &, 1594 llvm::SmallVectorImpl<llvm::Value *> &) {} 1595 1596 Address CodeGenFunction::OMPBuilderCBHelpers::getAddressOfLocalVariable( 1597 CodeGenFunction &CGF, const VarDecl *VD) { 1598 CodeGenModule &CGM = CGF.CGM; 1599 auto &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1600 1601 if (!VD) 1602 return Address::invalid(); 1603 const VarDecl *CVD = VD->getCanonicalDecl(); 1604 if (!isAllocatableDecl(CVD)) 1605 return Address::invalid(); 1606 llvm::Value *Size; 1607 CharUnits Align = CGM.getContext().getDeclAlign(CVD); 1608 if (CVD->getType()->isVariablyModifiedType()) { 1609 Size = CGF.getTypeSize(CVD->getType()); 1610 // Align the size: ((size + align - 1) / align) * align 1611 Size = CGF.Builder.CreateNUWAdd( 1612 Size, CGM.getSize(Align - CharUnits::fromQuantity(1))); 1613 Size = CGF.Builder.CreateUDiv(Size, CGM.getSize(Align)); 1614 Size = CGF.Builder.CreateNUWMul(Size, CGM.getSize(Align)); 1615 } else { 1616 CharUnits Sz = CGM.getContext().getTypeSizeInChars(CVD->getType()); 1617 Size = CGM.getSize(Sz.alignTo(Align)); 1618 } 1619 1620 const auto *AA = CVD->getAttr<OMPAllocateDeclAttr>(); 1621 assert(AA->getAllocator() && 1622 "Expected allocator expression for non-default allocator."); 1623 llvm::Value *Allocator = CGF.EmitScalarExpr(AA->getAllocator()); 1624 // According to the standard, the original allocator type is a enum (integer). 1625 // Convert to pointer type, if required. 1626 if (Allocator->getType()->isIntegerTy()) 1627 Allocator = CGF.Builder.CreateIntToPtr(Allocator, CGM.VoidPtrTy); 1628 else if (Allocator->getType()->isPointerTy()) 1629 Allocator = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Allocator, 1630 CGM.VoidPtrTy); 1631 1632 llvm::Value *Addr = OMPBuilder.createOMPAlloc( 1633 CGF.Builder, Size, Allocator, 1634 getNameWithSeparators({CVD->getName(), ".void.addr"}, ".", ".")); 1635 llvm::CallInst *FreeCI = 1636 OMPBuilder.createOMPFree(CGF.Builder, Addr, Allocator); 1637 1638 CGF.EHStack.pushCleanup<OMPAllocateCleanupTy>(NormalAndEHCleanup, FreeCI); 1639 Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 1640 Addr, 1641 CGF.ConvertTypeForMem(CGM.getContext().getPointerType(CVD->getType())), 1642 getNameWithSeparators({CVD->getName(), ".addr"}, ".", ".")); 1643 return Address(Addr, CGF.ConvertTypeForMem(CVD->getType()), Align); 1644 } 1645 1646 Address CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate( 1647 CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, 1648 SourceLocation Loc) { 1649 CodeGenModule &CGM = CGF.CGM; 1650 if (CGM.getLangOpts().OpenMPUseTLS && 1651 CGM.getContext().getTargetInfo().isTLSSupported()) 1652 return VDAddr; 1653 1654 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1655 1656 llvm::Type *VarTy = VDAddr.getElementType(); 1657 llvm::Value *Data = 1658 CGF.Builder.CreatePointerCast(VDAddr.getPointer(), CGM.Int8PtrTy); 1659 llvm::ConstantInt *Size = CGM.getSize(CGM.GetTargetTypeStoreSize(VarTy)); 1660 std::string Suffix = getNameWithSeparators({"cache", ""}); 1661 llvm::Twine CacheName = Twine(CGM.getMangledName(VD)).concat(Suffix); 1662 1663 llvm::CallInst *ThreadPrivateCacheCall = 1664 OMPBuilder.createCachedThreadPrivate(CGF.Builder, Data, Size, CacheName); 1665 1666 return Address(ThreadPrivateCacheCall, CGM.Int8Ty, VDAddr.getAlignment()); 1667 } 1668 1669 std::string CodeGenFunction::OMPBuilderCBHelpers::getNameWithSeparators( 1670 ArrayRef<StringRef> Parts, StringRef FirstSeparator, StringRef Separator) { 1671 SmallString<128> Buffer; 1672 llvm::raw_svector_ostream OS(Buffer); 1673 StringRef Sep = FirstSeparator; 1674 for (StringRef Part : Parts) { 1675 OS << Sep << Part; 1676 Sep = Separator; 1677 } 1678 return OS.str().str(); 1679 } 1680 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { 1681 if (CGM.getLangOpts().OpenMPIRBuilder) { 1682 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 1683 // Check if we have any if clause associated with the directive. 1684 llvm::Value *IfCond = nullptr; 1685 if (const auto *C = S.getSingleClause<OMPIfClause>()) 1686 IfCond = EmitScalarExpr(C->getCondition(), 1687 /*IgnoreResultAssign=*/true); 1688 1689 llvm::Value *NumThreads = nullptr; 1690 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) 1691 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(), 1692 /*IgnoreResultAssign=*/true); 1693 1694 ProcBindKind ProcBind = OMP_PROC_BIND_default; 1695 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) 1696 ProcBind = ProcBindClause->getProcBindKind(); 1697 1698 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 1699 1700 // The cleanup callback that finalizes all variabels at the given location, 1701 // thus calls destructors etc. 1702 auto FiniCB = [this](InsertPointTy IP) { 1703 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 1704 }; 1705 1706 // Privatization callback that performs appropriate action for 1707 // shared/private/firstprivate/lastprivate/copyin/... variables. 1708 // 1709 // TODO: This defaults to shared right now. 1710 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1711 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) { 1712 // The next line is appropriate only for variables (Val) with the 1713 // data-sharing attribute "shared". 1714 ReplVal = &Val; 1715 1716 return CodeGenIP; 1717 }; 1718 1719 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1720 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt(); 1721 1722 auto BodyGenCB = [ParallelRegionBodyStmt, 1723 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1724 llvm::BasicBlock &ContinuationBB) { 1725 OMPBuilderCBHelpers::OutlinedRegionBodyRAII ORB(*this, AllocaIP, 1726 ContinuationBB); 1727 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, ParallelRegionBodyStmt, 1728 CodeGenIP, ContinuationBB); 1729 }; 1730 1731 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 1732 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 1733 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 1734 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 1735 Builder.restoreIP( 1736 OMPBuilder.createParallel(Builder, AllocaIP, BodyGenCB, PrivCB, FiniCB, 1737 IfCond, NumThreads, ProcBind, S.hasCancel())); 1738 return; 1739 } 1740 1741 // Emit parallel region as a standalone region. 1742 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 1743 Action.Enter(CGF); 1744 OMPPrivateScope PrivateScope(CGF); 1745 bool Copyins = CGF.EmitOMPCopyinClause(S); 1746 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 1747 if (Copyins) { 1748 // Emit implicit barrier to synchronize threads and avoid data races on 1749 // propagation master's thread values of threadprivate variables to local 1750 // instances of that variables of all other implicit threads. 1751 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 1752 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 1753 /*ForceSimpleCall=*/true); 1754 } 1755 CGF.EmitOMPPrivateClause(S, PrivateScope); 1756 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 1757 (void)PrivateScope.Privatize(); 1758 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt()); 1759 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 1760 }; 1761 { 1762 auto LPCRegion = 1763 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 1764 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen, 1765 emitEmptyBoundParameters); 1766 emitPostUpdateForReductionClause(*this, S, 1767 [](CodeGenFunction &) { return nullptr; }); 1768 } 1769 // Check for outer lastprivate conditional update. 1770 checkForLastprivateConditionalUpdate(*this, S); 1771 } 1772 1773 void CodeGenFunction::EmitOMPMetaDirective(const OMPMetaDirective &S) { 1774 EmitStmt(S.getIfStmt()); 1775 } 1776 1777 namespace { 1778 /// RAII to handle scopes for loop transformation directives. 1779 class OMPTransformDirectiveScopeRAII { 1780 OMPLoopScope *Scope = nullptr; 1781 CodeGenFunction::CGCapturedStmtInfo *CGSI = nullptr; 1782 CodeGenFunction::CGCapturedStmtRAII *CapInfoRAII = nullptr; 1783 1784 public: 1785 OMPTransformDirectiveScopeRAII(CodeGenFunction &CGF, const Stmt *S) { 1786 if (const auto *Dir = dyn_cast<OMPLoopBasedDirective>(S)) { 1787 Scope = new OMPLoopScope(CGF, *Dir); 1788 CGSI = new CodeGenFunction::CGCapturedStmtInfo(CR_OpenMP); 1789 CapInfoRAII = new CodeGenFunction::CGCapturedStmtRAII(CGF, CGSI); 1790 } 1791 } 1792 ~OMPTransformDirectiveScopeRAII() { 1793 if (!Scope) 1794 return; 1795 delete CapInfoRAII; 1796 delete CGSI; 1797 delete Scope; 1798 } 1799 }; 1800 } // namespace 1801 1802 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop, 1803 int MaxLevel, int Level = 0) { 1804 assert(Level < MaxLevel && "Too deep lookup during loop body codegen."); 1805 const Stmt *SimplifiedS = S->IgnoreContainers(); 1806 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) { 1807 PrettyStackTraceLoc CrashInfo( 1808 CGF.getContext().getSourceManager(), CS->getLBracLoc(), 1809 "LLVM IR generation of compound statement ('{}')"); 1810 1811 // Keep track of the current cleanup stack depth, including debug scopes. 1812 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange()); 1813 for (const Stmt *CurStmt : CS->body()) 1814 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level); 1815 return; 1816 } 1817 if (SimplifiedS == NextLoop) { 1818 if (auto *Dir = dyn_cast<OMPLoopTransformationDirective>(SimplifiedS)) 1819 SimplifiedS = Dir->getTransformedStmt(); 1820 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(SimplifiedS)) 1821 SimplifiedS = CanonLoop->getLoopStmt(); 1822 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) { 1823 S = For->getBody(); 1824 } else { 1825 assert(isa<CXXForRangeStmt>(SimplifiedS) && 1826 "Expected canonical for loop or range-based for loop."); 1827 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS); 1828 CGF.EmitStmt(CXXFor->getLoopVarStmt()); 1829 S = CXXFor->getBody(); 1830 } 1831 if (Level + 1 < MaxLevel) { 1832 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop( 1833 S, /*TryImperfectlyNestedLoops=*/true); 1834 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1); 1835 return; 1836 } 1837 } 1838 CGF.EmitStmt(S); 1839 } 1840 1841 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D, 1842 JumpDest LoopExit) { 1843 RunCleanupsScope BodyScope(*this); 1844 // Update counters values on current iteration. 1845 for (const Expr *UE : D.updates()) 1846 EmitIgnoredExpr(UE); 1847 // Update the linear variables. 1848 // In distribute directives only loop counters may be marked as linear, no 1849 // need to generate the code for them. 1850 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) { 1851 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1852 for (const Expr *UE : C->updates()) 1853 EmitIgnoredExpr(UE); 1854 } 1855 } 1856 1857 // On a continue in the body, jump to the end. 1858 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue"); 1859 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1860 for (const Expr *E : D.finals_conditions()) { 1861 if (!E) 1862 continue; 1863 // Check that loop counter in non-rectangular nest fits into the iteration 1864 // space. 1865 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next"); 1866 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(), 1867 getProfileCount(D.getBody())); 1868 EmitBlock(NextBB); 1869 } 1870 1871 OMPPrivateScope InscanScope(*this); 1872 EmitOMPReductionClauseInit(D, InscanScope, /*ForInscan=*/true); 1873 bool IsInscanRegion = InscanScope.Privatize(); 1874 if (IsInscanRegion) { 1875 // Need to remember the block before and after scan directive 1876 // to dispatch them correctly depending on the clause used in 1877 // this directive, inclusive or exclusive. For inclusive scan the natural 1878 // order of the blocks is used, for exclusive clause the blocks must be 1879 // executed in reverse order. 1880 OMPBeforeScanBlock = createBasicBlock("omp.before.scan.bb"); 1881 OMPAfterScanBlock = createBasicBlock("omp.after.scan.bb"); 1882 // No need to allocate inscan exit block, in simd mode it is selected in the 1883 // codegen for the scan directive. 1884 if (D.getDirectiveKind() != OMPD_simd && !getLangOpts().OpenMPSimd) 1885 OMPScanExitBlock = createBasicBlock("omp.exit.inscan.bb"); 1886 OMPScanDispatch = createBasicBlock("omp.inscan.dispatch"); 1887 EmitBranch(OMPScanDispatch); 1888 EmitBlock(OMPBeforeScanBlock); 1889 } 1890 1891 // Emit loop variables for C++ range loops. 1892 const Stmt *Body = 1893 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); 1894 // Emit loop body. 1895 emitBody(*this, Body, 1896 OMPLoopBasedDirective::tryToFindNextInnerLoop( 1897 Body, /*TryImperfectlyNestedLoops=*/true), 1898 D.getLoopsNumber()); 1899 1900 // Jump to the dispatcher at the end of the loop body. 1901 if (IsInscanRegion) 1902 EmitBranch(OMPScanExitBlock); 1903 1904 // The end (updates/cleanups). 1905 EmitBlock(Continue.getBlock()); 1906 BreakContinueStack.pop_back(); 1907 } 1908 1909 using EmittedClosureTy = std::pair<llvm::Function *, llvm::Value *>; 1910 1911 /// Emit a captured statement and return the function as well as its captured 1912 /// closure context. 1913 static EmittedClosureTy emitCapturedStmtFunc(CodeGenFunction &ParentCGF, 1914 const CapturedStmt *S) { 1915 LValue CapStruct = ParentCGF.InitCapturedStruct(*S); 1916 CodeGenFunction CGF(ParentCGF.CGM, /*suppressNewContext=*/true); 1917 std::unique_ptr<CodeGenFunction::CGCapturedStmtInfo> CSI = 1918 std::make_unique<CodeGenFunction::CGCapturedStmtInfo>(*S); 1919 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, CSI.get()); 1920 llvm::Function *F = CGF.GenerateCapturedStmtFunction(*S); 1921 1922 return {F, CapStruct.getPointer(ParentCGF)}; 1923 } 1924 1925 /// Emit a call to a previously captured closure. 1926 static llvm::CallInst * 1927 emitCapturedStmtCall(CodeGenFunction &ParentCGF, EmittedClosureTy Cap, 1928 llvm::ArrayRef<llvm::Value *> Args) { 1929 // Append the closure context to the argument. 1930 SmallVector<llvm::Value *> EffectiveArgs; 1931 EffectiveArgs.reserve(Args.size() + 1); 1932 llvm::append_range(EffectiveArgs, Args); 1933 EffectiveArgs.push_back(Cap.second); 1934 1935 return ParentCGF.Builder.CreateCall(Cap.first, EffectiveArgs); 1936 } 1937 1938 llvm::CanonicalLoopInfo * 1939 CodeGenFunction::EmitOMPCollapsedCanonicalLoopNest(const Stmt *S, int Depth) { 1940 assert(Depth == 1 && "Nested loops with OpenMPIRBuilder not yet implemented"); 1941 1942 // The caller is processing the loop-associated directive processing the \p 1943 // Depth loops nested in \p S. Put the previous pending loop-associated 1944 // directive to the stack. If the current loop-associated directive is a loop 1945 // transformation directive, it will push its generated loops onto the stack 1946 // such that together with the loops left here they form the combined loop 1947 // nest for the parent loop-associated directive. 1948 int ParentExpectedOMPLoopDepth = ExpectedOMPLoopDepth; 1949 ExpectedOMPLoopDepth = Depth; 1950 1951 EmitStmt(S); 1952 assert(OMPLoopNestStack.size() >= (size_t)Depth && "Found too few loops"); 1953 1954 // The last added loop is the outermost one. 1955 llvm::CanonicalLoopInfo *Result = OMPLoopNestStack.back(); 1956 1957 // Pop the \p Depth loops requested by the call from that stack and restore 1958 // the previous context. 1959 OMPLoopNestStack.pop_back_n(Depth); 1960 ExpectedOMPLoopDepth = ParentExpectedOMPLoopDepth; 1961 1962 return Result; 1963 } 1964 1965 void CodeGenFunction::EmitOMPCanonicalLoop(const OMPCanonicalLoop *S) { 1966 const Stmt *SyntacticalLoop = S->getLoopStmt(); 1967 if (!getLangOpts().OpenMPIRBuilder) { 1968 // Ignore if OpenMPIRBuilder is not enabled. 1969 EmitStmt(SyntacticalLoop); 1970 return; 1971 } 1972 1973 LexicalScope ForScope(*this, S->getSourceRange()); 1974 1975 // Emit init statements. The Distance/LoopVar funcs may reference variable 1976 // declarations they contain. 1977 const Stmt *BodyStmt; 1978 if (const auto *For = dyn_cast<ForStmt>(SyntacticalLoop)) { 1979 if (const Stmt *InitStmt = For->getInit()) 1980 EmitStmt(InitStmt); 1981 BodyStmt = For->getBody(); 1982 } else if (const auto *RangeFor = 1983 dyn_cast<CXXForRangeStmt>(SyntacticalLoop)) { 1984 if (const DeclStmt *RangeStmt = RangeFor->getRangeStmt()) 1985 EmitStmt(RangeStmt); 1986 if (const DeclStmt *BeginStmt = RangeFor->getBeginStmt()) 1987 EmitStmt(BeginStmt); 1988 if (const DeclStmt *EndStmt = RangeFor->getEndStmt()) 1989 EmitStmt(EndStmt); 1990 if (const DeclStmt *LoopVarStmt = RangeFor->getLoopVarStmt()) 1991 EmitStmt(LoopVarStmt); 1992 BodyStmt = RangeFor->getBody(); 1993 } else 1994 llvm_unreachable("Expected for-stmt or range-based for-stmt"); 1995 1996 // Emit closure for later use. By-value captures will be captured here. 1997 const CapturedStmt *DistanceFunc = S->getDistanceFunc(); 1998 EmittedClosureTy DistanceClosure = emitCapturedStmtFunc(*this, DistanceFunc); 1999 const CapturedStmt *LoopVarFunc = S->getLoopVarFunc(); 2000 EmittedClosureTy LoopVarClosure = emitCapturedStmtFunc(*this, LoopVarFunc); 2001 2002 // Call the distance function to get the number of iterations of the loop to 2003 // come. 2004 QualType LogicalTy = DistanceFunc->getCapturedDecl() 2005 ->getParam(0) 2006 ->getType() 2007 .getNonReferenceType(); 2008 Address CountAddr = CreateMemTemp(LogicalTy, ".count.addr"); 2009 emitCapturedStmtCall(*this, DistanceClosure, {CountAddr.getPointer()}); 2010 llvm::Value *DistVal = Builder.CreateLoad(CountAddr, ".count"); 2011 2012 // Emit the loop structure. 2013 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 2014 auto BodyGen = [&, this](llvm::OpenMPIRBuilder::InsertPointTy CodeGenIP, 2015 llvm::Value *IndVar) { 2016 Builder.restoreIP(CodeGenIP); 2017 2018 // Emit the loop body: Convert the logical iteration number to the loop 2019 // variable and emit the body. 2020 const DeclRefExpr *LoopVarRef = S->getLoopVarRef(); 2021 LValue LCVal = EmitLValue(LoopVarRef); 2022 Address LoopVarAddress = LCVal.getAddress(*this); 2023 emitCapturedStmtCall(*this, LoopVarClosure, 2024 {LoopVarAddress.getPointer(), IndVar}); 2025 2026 RunCleanupsScope BodyScope(*this); 2027 EmitStmt(BodyStmt); 2028 }; 2029 llvm::CanonicalLoopInfo *CL = 2030 OMPBuilder.createCanonicalLoop(Builder, BodyGen, DistVal); 2031 2032 // Finish up the loop. 2033 Builder.restoreIP(CL->getAfterIP()); 2034 ForScope.ForceCleanup(); 2035 2036 // Remember the CanonicalLoopInfo for parent AST nodes consuming it. 2037 OMPLoopNestStack.push_back(CL); 2038 } 2039 2040 void CodeGenFunction::EmitOMPInnerLoop( 2041 const OMPExecutableDirective &S, bool RequiresCleanup, const Expr *LoopCond, 2042 const Expr *IncExpr, 2043 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 2044 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) { 2045 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 2046 2047 // Start the loop with a block that tests the condition. 2048 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 2049 EmitBlock(CondBlock); 2050 const SourceRange R = S.getSourceRange(); 2051 2052 // If attributes are attached, push to the basic block with them. 2053 const auto &OMPED = cast<OMPExecutableDirective>(S); 2054 const CapturedStmt *ICS = OMPED.getInnermostCapturedStmt(); 2055 const Stmt *SS = ICS->getCapturedStmt(); 2056 const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(SS); 2057 OMPLoopNestStack.clear(); 2058 if (AS) 2059 LoopStack.push(CondBlock, CGM.getContext(), CGM.getCodeGenOpts(), 2060 AS->getAttrs(), SourceLocToDebugLoc(R.getBegin()), 2061 SourceLocToDebugLoc(R.getEnd())); 2062 else 2063 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2064 SourceLocToDebugLoc(R.getEnd())); 2065 2066 // If there are any cleanups between here and the loop-exit scope, 2067 // create a block to stage a loop exit along. 2068 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2069 if (RequiresCleanup) 2070 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 2071 2072 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body"); 2073 2074 // Emit condition. 2075 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 2076 if (ExitBlock != LoopExit.getBlock()) { 2077 EmitBlock(ExitBlock); 2078 EmitBranchThroughCleanup(LoopExit); 2079 } 2080 2081 EmitBlock(LoopBody); 2082 incrementProfileCounter(&S); 2083 2084 // Create a block for the increment. 2085 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 2086 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2087 2088 BodyGen(*this); 2089 2090 // Emit "IV = IV + 1" and a back-edge to the condition block. 2091 EmitBlock(Continue.getBlock()); 2092 EmitIgnoredExpr(IncExpr); 2093 PostIncGen(*this); 2094 BreakContinueStack.pop_back(); 2095 EmitBranch(CondBlock); 2096 LoopStack.pop(); 2097 // Emit the fall-through block. 2098 EmitBlock(LoopExit.getBlock()); 2099 } 2100 2101 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) { 2102 if (!HaveInsertPoint()) 2103 return false; 2104 // Emit inits for the linear variables. 2105 bool HasLinears = false; 2106 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2107 for (const Expr *Init : C->inits()) { 2108 HasLinears = true; 2109 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 2110 if (const auto *Ref = 2111 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) { 2112 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 2113 const auto *OrigVD = cast<VarDecl>(Ref->getDecl()); 2114 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 2115 CapturedStmtInfo->lookup(OrigVD) != nullptr, 2116 VD->getInit()->getType(), VK_LValue, 2117 VD->getInit()->getExprLoc()); 2118 EmitExprAsInit( 2119 &DRE, VD, 2120 MakeAddrLValue(Emission.getAllocatedAddress(), VD->getType()), 2121 /*capturedByInit=*/false); 2122 EmitAutoVarCleanups(Emission); 2123 } else { 2124 EmitVarDecl(*VD); 2125 } 2126 } 2127 // Emit the linear steps for the linear clauses. 2128 // If a step is not constant, it is pre-calculated before the loop. 2129 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 2130 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 2131 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 2132 // Emit calculation of the linear step. 2133 EmitIgnoredExpr(CS); 2134 } 2135 } 2136 return HasLinears; 2137 } 2138 2139 void CodeGenFunction::EmitOMPLinearClauseFinal( 2140 const OMPLoopDirective &D, 2141 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 2142 if (!HaveInsertPoint()) 2143 return; 2144 llvm::BasicBlock *DoneBB = nullptr; 2145 // Emit the final values of the linear variables. 2146 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2147 auto IC = C->varlist_begin(); 2148 for (const Expr *F : C->finals()) { 2149 if (!DoneBB) { 2150 if (llvm::Value *Cond = CondGen(*this)) { 2151 // If the first post-update expression is found, emit conditional 2152 // block if it was requested. 2153 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu"); 2154 DoneBB = createBasicBlock(".omp.linear.pu.done"); 2155 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 2156 EmitBlock(ThenBB); 2157 } 2158 } 2159 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 2160 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 2161 CapturedStmtInfo->lookup(OrigVD) != nullptr, 2162 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 2163 Address OrigAddr = EmitLValue(&DRE).getAddress(*this); 2164 CodeGenFunction::OMPPrivateScope VarScope(*this); 2165 VarScope.addPrivate(OrigVD, OrigAddr); 2166 (void)VarScope.Privatize(); 2167 EmitIgnoredExpr(F); 2168 ++IC; 2169 } 2170 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 2171 EmitIgnoredExpr(PostUpdate); 2172 } 2173 if (DoneBB) 2174 EmitBlock(DoneBB, /*IsFinished=*/true); 2175 } 2176 2177 static void emitAlignedClause(CodeGenFunction &CGF, 2178 const OMPExecutableDirective &D) { 2179 if (!CGF.HaveInsertPoint()) 2180 return; 2181 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) { 2182 llvm::APInt ClauseAlignment(64, 0); 2183 if (const Expr *AlignmentExpr = Clause->getAlignment()) { 2184 auto *AlignmentCI = 2185 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 2186 ClauseAlignment = AlignmentCI->getValue(); 2187 } 2188 for (const Expr *E : Clause->varlists()) { 2189 llvm::APInt Alignment(ClauseAlignment); 2190 if (Alignment == 0) { 2191 // OpenMP [2.8.1, Description] 2192 // If no optional parameter is specified, implementation-defined default 2193 // alignments for SIMD instructions on the target platforms are assumed. 2194 Alignment = 2195 CGF.getContext() 2196 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 2197 E->getType()->getPointeeType())) 2198 .getQuantity(); 2199 } 2200 assert((Alignment == 0 || Alignment.isPowerOf2()) && 2201 "alignment is not power of 2"); 2202 if (Alignment != 0) { 2203 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 2204 CGF.emitAlignmentAssumption( 2205 PtrValue, E, /*No second loc needed*/ SourceLocation(), 2206 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment)); 2207 } 2208 } 2209 } 2210 } 2211 2212 void CodeGenFunction::EmitOMPPrivateLoopCounters( 2213 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) { 2214 if (!HaveInsertPoint()) 2215 return; 2216 auto I = S.private_counters().begin(); 2217 for (const Expr *E : S.counters()) { 2218 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2219 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()); 2220 // Emit var without initialization. 2221 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD); 2222 EmitAutoVarCleanups(VarEmission); 2223 LocalDeclMap.erase(PrivateVD); 2224 (void)LoopScope.addPrivate(VD, VarEmission.getAllocatedAddress()); 2225 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) || 2226 VD->hasGlobalStorage()) { 2227 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), 2228 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD), 2229 E->getType(), VK_LValue, E->getExprLoc()); 2230 (void)LoopScope.addPrivate(PrivateVD, EmitLValue(&DRE).getAddress(*this)); 2231 } else { 2232 (void)LoopScope.addPrivate(PrivateVD, VarEmission.getAllocatedAddress()); 2233 } 2234 ++I; 2235 } 2236 // Privatize extra loop counters used in loops for ordered(n) clauses. 2237 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) { 2238 if (!C->getNumForLoops()) 2239 continue; 2240 for (unsigned I = S.getLoopsNumber(), E = C->getLoopNumIterations().size(); 2241 I < E; ++I) { 2242 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I)); 2243 const auto *VD = cast<VarDecl>(DRE->getDecl()); 2244 // Override only those variables that can be captured to avoid re-emission 2245 // of the variables declared within the loops. 2246 if (DRE->refersToEnclosingVariableOrCapture()) { 2247 (void)LoopScope.addPrivate( 2248 VD, CreateMemTemp(DRE->getType(), VD->getName())); 2249 } 2250 } 2251 } 2252 } 2253 2254 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 2255 const Expr *Cond, llvm::BasicBlock *TrueBlock, 2256 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 2257 if (!CGF.HaveInsertPoint()) 2258 return; 2259 { 2260 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 2261 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope); 2262 (void)PreCondScope.Privatize(); 2263 // Get initial values of real counters. 2264 for (const Expr *I : S.inits()) { 2265 CGF.EmitIgnoredExpr(I); 2266 } 2267 } 2268 // Create temp loop control variables with their init values to support 2269 // non-rectangular loops. 2270 CodeGenFunction::OMPMapVars PreCondVars; 2271 for (const Expr *E : S.dependent_counters()) { 2272 if (!E) 2273 continue; 2274 assert(!E->getType().getNonReferenceType()->isRecordType() && 2275 "dependent counter must not be an iterator."); 2276 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2277 Address CounterAddr = 2278 CGF.CreateMemTemp(VD->getType().getNonReferenceType()); 2279 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr); 2280 } 2281 (void)PreCondVars.apply(CGF); 2282 for (const Expr *E : S.dependent_inits()) { 2283 if (!E) 2284 continue; 2285 CGF.EmitIgnoredExpr(E); 2286 } 2287 // Check that loop is executed at least one time. 2288 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 2289 PreCondVars.restore(CGF); 2290 } 2291 2292 void CodeGenFunction::EmitOMPLinearClause( 2293 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) { 2294 if (!HaveInsertPoint()) 2295 return; 2296 llvm::DenseSet<const VarDecl *> SIMDLCVs; 2297 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 2298 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 2299 for (const Expr *C : LoopDirective->counters()) { 2300 SIMDLCVs.insert( 2301 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 2302 } 2303 } 2304 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 2305 auto CurPrivate = C->privates().begin(); 2306 for (const Expr *E : C->varlists()) { 2307 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 2308 const auto *PrivateVD = 2309 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl()); 2310 if (!SIMDLCVs.count(VD->getCanonicalDecl())) { 2311 // Emit private VarDecl with copy init. 2312 EmitVarDecl(*PrivateVD); 2313 bool IsRegistered = 2314 PrivateScope.addPrivate(VD, GetAddrOfLocalVar(PrivateVD)); 2315 assert(IsRegistered && "linear var already registered as private"); 2316 // Silence the warning about unused variable. 2317 (void)IsRegistered; 2318 } else { 2319 EmitVarDecl(*PrivateVD); 2320 } 2321 ++CurPrivate; 2322 } 2323 } 2324 } 2325 2326 static void emitSimdlenSafelenClause(CodeGenFunction &CGF, 2327 const OMPExecutableDirective &D) { 2328 if (!CGF.HaveInsertPoint()) 2329 return; 2330 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) { 2331 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(), 2332 /*ignoreResult=*/true); 2333 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 2334 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 2335 // In presence of finite 'safelen', it may be unsafe to mark all 2336 // the memory instructions parallel, because loop-carried 2337 // dependences of 'safelen' iterations are possible. 2338 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>()); 2339 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) { 2340 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(), 2341 /*ignoreResult=*/true); 2342 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 2343 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 2344 // In presence of finite 'safelen', it may be unsafe to mark all 2345 // the memory instructions parallel, because loop-carried 2346 // dependences of 'safelen' iterations are possible. 2347 CGF.LoopStack.setParallel(/*Enable=*/false); 2348 } 2349 } 2350 2351 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D) { 2352 // Walk clauses and process safelen/lastprivate. 2353 LoopStack.setParallel(/*Enable=*/true); 2354 LoopStack.setVectorizeEnable(); 2355 emitSimdlenSafelenClause(*this, D); 2356 if (const auto *C = D.getSingleClause<OMPOrderClause>()) 2357 if (C->getKind() == OMPC_ORDER_concurrent) 2358 LoopStack.setParallel(/*Enable=*/true); 2359 if ((D.getDirectiveKind() == OMPD_simd || 2360 (getLangOpts().OpenMPSimd && 2361 isOpenMPSimdDirective(D.getDirectiveKind()))) && 2362 llvm::any_of(D.getClausesOfKind<OMPReductionClause>(), 2363 [](const OMPReductionClause *C) { 2364 return C->getModifier() == OMPC_REDUCTION_inscan; 2365 })) 2366 // Disable parallel access in case of prefix sum. 2367 LoopStack.setParallel(/*Enable=*/false); 2368 } 2369 2370 void CodeGenFunction::EmitOMPSimdFinal( 2371 const OMPLoopDirective &D, 2372 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 2373 if (!HaveInsertPoint()) 2374 return; 2375 llvm::BasicBlock *DoneBB = nullptr; 2376 auto IC = D.counters().begin(); 2377 auto IPC = D.private_counters().begin(); 2378 for (const Expr *F : D.finals()) { 2379 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 2380 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl()); 2381 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD); 2382 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) || 2383 OrigVD->hasGlobalStorage() || CED) { 2384 if (!DoneBB) { 2385 if (llvm::Value *Cond = CondGen(*this)) { 2386 // If the first post-update expression is found, emit conditional 2387 // block if it was requested. 2388 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then"); 2389 DoneBB = createBasicBlock(".omp.final.done"); 2390 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 2391 EmitBlock(ThenBB); 2392 } 2393 } 2394 Address OrigAddr = Address::invalid(); 2395 if (CED) { 2396 OrigAddr = 2397 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this); 2398 } else { 2399 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD), 2400 /*RefersToEnclosingVariableOrCapture=*/false, 2401 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc()); 2402 OrigAddr = EmitLValue(&DRE).getAddress(*this); 2403 } 2404 OMPPrivateScope VarScope(*this); 2405 VarScope.addPrivate(OrigVD, OrigAddr); 2406 (void)VarScope.Privatize(); 2407 EmitIgnoredExpr(F); 2408 } 2409 ++IC; 2410 ++IPC; 2411 } 2412 if (DoneBB) 2413 EmitBlock(DoneBB, /*IsFinished=*/true); 2414 } 2415 2416 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF, 2417 const OMPLoopDirective &S, 2418 CodeGenFunction::JumpDest LoopExit) { 2419 CGF.EmitOMPLoopBody(S, LoopExit); 2420 CGF.EmitStopPoint(&S); 2421 } 2422 2423 /// Emit a helper variable and return corresponding lvalue. 2424 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 2425 const DeclRefExpr *Helper) { 2426 auto VDecl = cast<VarDecl>(Helper->getDecl()); 2427 CGF.EmitVarDecl(*VDecl); 2428 return CGF.EmitLValue(Helper); 2429 } 2430 2431 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S, 2432 const RegionCodeGenTy &SimdInitGen, 2433 const RegionCodeGenTy &BodyCodeGen) { 2434 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF, 2435 PrePostActionTy &) { 2436 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S); 2437 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2438 SimdInitGen(CGF); 2439 2440 BodyCodeGen(CGF); 2441 }; 2442 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) { 2443 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2444 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false); 2445 2446 BodyCodeGen(CGF); 2447 }; 2448 const Expr *IfCond = nullptr; 2449 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2450 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 2451 if (CGF.getLangOpts().OpenMP >= 50 && 2452 (C->getNameModifier() == OMPD_unknown || 2453 C->getNameModifier() == OMPD_simd)) { 2454 IfCond = C->getCondition(); 2455 break; 2456 } 2457 } 2458 } 2459 if (IfCond) { 2460 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen); 2461 } else { 2462 RegionCodeGenTy ThenRCG(ThenGen); 2463 ThenRCG(CGF); 2464 } 2465 } 2466 2467 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, 2468 PrePostActionTy &Action) { 2469 Action.Enter(CGF); 2470 assert(isOpenMPSimdDirective(S.getDirectiveKind()) && 2471 "Expected simd directive"); 2472 OMPLoopScope PreInitScope(CGF, S); 2473 // if (PreCond) { 2474 // for (IV in 0..LastIteration) BODY; 2475 // <Final counter/linear vars updates>; 2476 // } 2477 // 2478 if (isOpenMPDistributeDirective(S.getDirectiveKind()) || 2479 isOpenMPWorksharingDirective(S.getDirectiveKind()) || 2480 isOpenMPTaskLoopDirective(S.getDirectiveKind())) { 2481 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable())); 2482 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable())); 2483 } 2484 2485 // Emit: if (PreCond) - begin. 2486 // If the condition constant folds and can be elided, avoid emitting the 2487 // whole loop. 2488 bool CondConstant; 2489 llvm::BasicBlock *ContBlock = nullptr; 2490 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2491 if (!CondConstant) 2492 return; 2493 } else { 2494 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then"); 2495 ContBlock = CGF.createBasicBlock("simd.if.end"); 2496 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 2497 CGF.getProfileCount(&S)); 2498 CGF.EmitBlock(ThenBlock); 2499 CGF.incrementProfileCounter(&S); 2500 } 2501 2502 // Emit the loop iteration variable. 2503 const Expr *IVExpr = S.getIterationVariable(); 2504 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 2505 CGF.EmitVarDecl(*IVDecl); 2506 CGF.EmitIgnoredExpr(S.getInit()); 2507 2508 // Emit the iterations count variable. 2509 // If it is not a variable, Sema decided to calculate iterations count on 2510 // each iteration (e.g., it is foldable into a constant). 2511 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2512 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2513 // Emit calculation of the iterations count. 2514 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 2515 } 2516 2517 emitAlignedClause(CGF, S); 2518 (void)CGF.EmitOMPLinearClauseInit(S); 2519 { 2520 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2521 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 2522 CGF.EmitOMPLinearClause(S, LoopScope); 2523 CGF.EmitOMPPrivateClause(S, LoopScope); 2524 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2525 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 2526 CGF, S, CGF.EmitLValue(S.getIterationVariable())); 2527 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2528 (void)LoopScope.Privatize(); 2529 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2530 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 2531 2532 emitCommonSimdLoop( 2533 CGF, S, 2534 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2535 CGF.EmitOMPSimdInit(S); 2536 }, 2537 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2538 CGF.EmitOMPInnerLoop( 2539 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 2540 [&S](CodeGenFunction &CGF) { 2541 emitOMPLoopBodyWithStopPoint(CGF, S, 2542 CodeGenFunction::JumpDest()); 2543 }, 2544 [](CodeGenFunction &) {}); 2545 }); 2546 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; }); 2547 // Emit final copy of the lastprivate variables at the end of loops. 2548 if (HasLastprivateClause) 2549 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true); 2550 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd); 2551 emitPostUpdateForReductionClause(CGF, S, 2552 [](CodeGenFunction &) { return nullptr; }); 2553 } 2554 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; }); 2555 // Emit: if (PreCond) - end. 2556 if (ContBlock) { 2557 CGF.EmitBranch(ContBlock); 2558 CGF.EmitBlock(ContBlock, true); 2559 } 2560 } 2561 2562 static bool isSupportedByOpenMPIRBuilder(const OMPExecutableDirective &S) { 2563 // Check for unsupported clauses 2564 if (!S.clauses().empty()) { 2565 // Currently no clause is supported 2566 return false; 2567 } 2568 2569 // Check if we have a statement with the ordered directive. 2570 // Visit the statement hierarchy to find a compound statement 2571 // with a ordered directive in it. 2572 if (const auto *CanonLoop = dyn_cast<OMPCanonicalLoop>(S.getRawStmt())) { 2573 if (const Stmt *SyntacticalLoop = CanonLoop->getLoopStmt()) { 2574 for (const Stmt *SubStmt : SyntacticalLoop->children()) { 2575 if (!SubStmt) 2576 continue; 2577 if (const CompoundStmt *CS = dyn_cast<CompoundStmt>(SubStmt)) { 2578 for (const Stmt *CSSubStmt : CS->children()) { 2579 if (!CSSubStmt) 2580 continue; 2581 if (isa<OMPOrderedDirective>(CSSubStmt)) { 2582 return false; 2583 } 2584 } 2585 } 2586 } 2587 } 2588 } 2589 return true; 2590 } 2591 2592 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 2593 bool UseOMPIRBuilder = 2594 CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S); 2595 if (UseOMPIRBuilder) { 2596 auto &&CodeGenIRBuilder = [this, &S, UseOMPIRBuilder](CodeGenFunction &CGF, 2597 PrePostActionTy &) { 2598 // Use the OpenMPIRBuilder if enabled. 2599 if (UseOMPIRBuilder) { 2600 // Emit the associated statement and get its loop representation. 2601 llvm::DebugLoc DL = SourceLocToDebugLoc(S.getBeginLoc()); 2602 const Stmt *Inner = S.getRawStmt(); 2603 llvm::CanonicalLoopInfo *CLI = 2604 EmitOMPCollapsedCanonicalLoopNest(Inner, 1); 2605 2606 llvm::OpenMPIRBuilder &OMPBuilder = 2607 CGM.getOpenMPRuntime().getOMPBuilder(); 2608 // Add SIMD specific metadata 2609 OMPBuilder.applySimd(DL, CLI); 2610 return; 2611 } 2612 }; 2613 { 2614 auto LPCRegion = 2615 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2616 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2617 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, 2618 CodeGenIRBuilder); 2619 } 2620 return; 2621 } 2622 2623 ParentLoopDirectiveForScanRegion ScanRegion(*this, S); 2624 OMPFirstScanLoop = true; 2625 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2626 emitOMPSimdRegion(CGF, S, Action); 2627 }; 2628 { 2629 auto LPCRegion = 2630 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2631 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2632 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2633 } 2634 // Check for outer lastprivate conditional update. 2635 checkForLastprivateConditionalUpdate(*this, S); 2636 } 2637 2638 void CodeGenFunction::EmitOMPTileDirective(const OMPTileDirective &S) { 2639 // Emit the de-sugared statement. 2640 OMPTransformDirectiveScopeRAII TileScope(*this, &S); 2641 EmitStmt(S.getTransformedStmt()); 2642 } 2643 2644 void CodeGenFunction::EmitOMPUnrollDirective(const OMPUnrollDirective &S) { 2645 bool UseOMPIRBuilder = CGM.getLangOpts().OpenMPIRBuilder; 2646 2647 if (UseOMPIRBuilder) { 2648 auto DL = SourceLocToDebugLoc(S.getBeginLoc()); 2649 const Stmt *Inner = S.getRawStmt(); 2650 2651 // Consume nested loop. Clear the entire remaining loop stack because a 2652 // fully unrolled loop is non-transformable. For partial unrolling the 2653 // generated outer loop is pushed back to the stack. 2654 llvm::CanonicalLoopInfo *CLI = EmitOMPCollapsedCanonicalLoopNest(Inner, 1); 2655 OMPLoopNestStack.clear(); 2656 2657 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 2658 2659 bool NeedsUnrolledCLI = ExpectedOMPLoopDepth >= 1; 2660 llvm::CanonicalLoopInfo *UnrolledCLI = nullptr; 2661 2662 if (S.hasClausesOfKind<OMPFullClause>()) { 2663 assert(ExpectedOMPLoopDepth == 0); 2664 OMPBuilder.unrollLoopFull(DL, CLI); 2665 } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) { 2666 uint64_t Factor = 0; 2667 if (Expr *FactorExpr = PartialClause->getFactor()) { 2668 Factor = FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue(); 2669 assert(Factor >= 1 && "Only positive factors are valid"); 2670 } 2671 OMPBuilder.unrollLoopPartial(DL, CLI, Factor, 2672 NeedsUnrolledCLI ? &UnrolledCLI : nullptr); 2673 } else { 2674 OMPBuilder.unrollLoopHeuristic(DL, CLI); 2675 } 2676 2677 assert((!NeedsUnrolledCLI || UnrolledCLI) && 2678 "NeedsUnrolledCLI implies UnrolledCLI to be set"); 2679 if (UnrolledCLI) 2680 OMPLoopNestStack.push_back(UnrolledCLI); 2681 2682 return; 2683 } 2684 2685 // This function is only called if the unrolled loop is not consumed by any 2686 // other loop-associated construct. Such a loop-associated construct will have 2687 // used the transformed AST. 2688 2689 // Set the unroll metadata for the next emitted loop. 2690 LoopStack.setUnrollState(LoopAttributes::Enable); 2691 2692 if (S.hasClausesOfKind<OMPFullClause>()) { 2693 LoopStack.setUnrollState(LoopAttributes::Full); 2694 } else if (auto *PartialClause = S.getSingleClause<OMPPartialClause>()) { 2695 if (Expr *FactorExpr = PartialClause->getFactor()) { 2696 uint64_t Factor = 2697 FactorExpr->EvaluateKnownConstInt(getContext()).getZExtValue(); 2698 assert(Factor >= 1 && "Only positive factors are valid"); 2699 LoopStack.setUnrollCount(Factor); 2700 } 2701 } 2702 2703 EmitStmt(S.getAssociatedStmt()); 2704 } 2705 2706 void CodeGenFunction::EmitOMPOuterLoop( 2707 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S, 2708 CodeGenFunction::OMPPrivateScope &LoopScope, 2709 const CodeGenFunction::OMPLoopArguments &LoopArgs, 2710 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop, 2711 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) { 2712 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2713 2714 const Expr *IVExpr = S.getIterationVariable(); 2715 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2716 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2717 2718 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 2719 2720 // Start the loop with a block that tests the condition. 2721 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond"); 2722 EmitBlock(CondBlock); 2723 const SourceRange R = S.getSourceRange(); 2724 OMPLoopNestStack.clear(); 2725 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2726 SourceLocToDebugLoc(R.getEnd())); 2727 2728 llvm::Value *BoolCondVal = nullptr; 2729 if (!DynamicOrOrdered) { 2730 // UB = min(UB, GlobalUB) or 2731 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g. 2732 // 'distribute parallel for') 2733 EmitIgnoredExpr(LoopArgs.EUB); 2734 // IV = LB 2735 EmitIgnoredExpr(LoopArgs.Init); 2736 // IV < UB 2737 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond); 2738 } else { 2739 BoolCondVal = 2740 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL, 2741 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST); 2742 } 2743 2744 // If there are any cleanups between here and the loop-exit scope, 2745 // create a block to stage a loop exit along. 2746 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2747 if (LoopScope.requiresCleanups()) 2748 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 2749 2750 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body"); 2751 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 2752 if (ExitBlock != LoopExit.getBlock()) { 2753 EmitBlock(ExitBlock); 2754 EmitBranchThroughCleanup(LoopExit); 2755 } 2756 EmitBlock(LoopBody); 2757 2758 // Emit "IV = LB" (in case of static schedule, we have already calculated new 2759 // LB for loop condition and emitted it above). 2760 if (DynamicOrOrdered) 2761 EmitIgnoredExpr(LoopArgs.Init); 2762 2763 // Create a block for the increment. 2764 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 2765 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2766 2767 emitCommonSimdLoop( 2768 *this, S, 2769 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) { 2770 // Generate !llvm.loop.parallel metadata for loads and stores for loops 2771 // with dynamic/guided scheduling and without ordered clause. 2772 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2773 CGF.LoopStack.setParallel(!IsMonotonic); 2774 if (const auto *C = S.getSingleClause<OMPOrderClause>()) 2775 if (C->getKind() == OMPC_ORDER_concurrent) 2776 CGF.LoopStack.setParallel(/*Enable=*/true); 2777 } else { 2778 CGF.EmitOMPSimdInit(S); 2779 } 2780 }, 2781 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered, 2782 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2783 SourceLocation Loc = S.getBeginLoc(); 2784 // when 'distribute' is not combined with a 'for': 2785 // while (idx <= UB) { BODY; ++idx; } 2786 // when 'distribute' is combined with a 'for' 2787 // (e.g. 'distribute parallel for') 2788 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; } 2789 CGF.EmitOMPInnerLoop( 2790 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr, 2791 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 2792 CodeGenLoop(CGF, S, LoopExit); 2793 }, 2794 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) { 2795 CodeGenOrdered(CGF, Loc, IVSize, IVSigned); 2796 }); 2797 }); 2798 2799 EmitBlock(Continue.getBlock()); 2800 BreakContinueStack.pop_back(); 2801 if (!DynamicOrOrdered) { 2802 // Emit "LB = LB + Stride", "UB = UB + Stride". 2803 EmitIgnoredExpr(LoopArgs.NextLB); 2804 EmitIgnoredExpr(LoopArgs.NextUB); 2805 } 2806 2807 EmitBranch(CondBlock); 2808 OMPLoopNestStack.clear(); 2809 LoopStack.pop(); 2810 // Emit the fall-through block. 2811 EmitBlock(LoopExit.getBlock()); 2812 2813 // Tell the runtime we are done. 2814 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) { 2815 if (!DynamicOrOrdered) 2816 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 2817 S.getDirectiveKind()); 2818 }; 2819 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2820 } 2821 2822 void CodeGenFunction::EmitOMPForOuterLoop( 2823 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic, 2824 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 2825 const OMPLoopArguments &LoopArgs, 2826 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 2827 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2828 2829 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 2830 const bool DynamicOrOrdered = Ordered || RT.isDynamic(ScheduleKind.Schedule); 2831 2832 assert((Ordered || !RT.isStaticNonchunked(ScheduleKind.Schedule, 2833 LoopArgs.Chunk != nullptr)) && 2834 "static non-chunked schedule does not need outer loop"); 2835 2836 // Emit outer loop. 2837 // 2838 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2839 // When schedule(dynamic,chunk_size) is specified, the iterations are 2840 // distributed to threads in the team in chunks as the threads request them. 2841 // Each thread executes a chunk of iterations, then requests another chunk, 2842 // until no chunks remain to be distributed. Each chunk contains chunk_size 2843 // iterations, except for the last chunk to be distributed, which may have 2844 // fewer iterations. When no chunk_size is specified, it defaults to 1. 2845 // 2846 // When schedule(guided,chunk_size) is specified, the iterations are assigned 2847 // to threads in the team in chunks as the executing threads request them. 2848 // Each thread executes a chunk of iterations, then requests another chunk, 2849 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 2850 // each chunk is proportional to the number of unassigned iterations divided 2851 // by the number of threads in the team, decreasing to 1. For a chunk_size 2852 // with value k (greater than 1), the size of each chunk is determined in the 2853 // same way, with the restriction that the chunks do not contain fewer than k 2854 // iterations (except for the last chunk to be assigned, which may have fewer 2855 // than k iterations). 2856 // 2857 // When schedule(auto) is specified, the decision regarding scheduling is 2858 // delegated to the compiler and/or runtime system. The programmer gives the 2859 // implementation the freedom to choose any possible mapping of iterations to 2860 // threads in the team. 2861 // 2862 // When schedule(runtime) is specified, the decision regarding scheduling is 2863 // deferred until run time, and the schedule and chunk size are taken from the 2864 // run-sched-var ICV. If the ICV is set to auto, the schedule is 2865 // implementation defined 2866 // 2867 // while(__kmpc_dispatch_next(&LB, &UB)) { 2868 // idx = LB; 2869 // while (idx <= UB) { BODY; ++idx; 2870 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 2871 // } // inner loop 2872 // } 2873 // 2874 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2875 // When schedule(static, chunk_size) is specified, iterations are divided into 2876 // chunks of size chunk_size, and the chunks are assigned to the threads in 2877 // the team in a round-robin fashion in the order of the thread number. 2878 // 2879 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 2880 // while (idx <= UB) { BODY; ++idx; } // inner loop 2881 // LB = LB + ST; 2882 // UB = UB + ST; 2883 // } 2884 // 2885 2886 const Expr *IVExpr = S.getIterationVariable(); 2887 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2888 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2889 2890 if (DynamicOrOrdered) { 2891 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds = 2892 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB); 2893 llvm::Value *LBVal = DispatchBounds.first; 2894 llvm::Value *UBVal = DispatchBounds.second; 2895 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal, 2896 LoopArgs.Chunk}; 2897 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize, 2898 IVSigned, Ordered, DipatchRTInputValues); 2899 } else { 2900 CGOpenMPRuntime::StaticRTInput StaticInit( 2901 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB, 2902 LoopArgs.ST, LoopArgs.Chunk); 2903 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(), 2904 ScheduleKind, StaticInit); 2905 } 2906 2907 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc, 2908 const unsigned IVSize, 2909 const bool IVSigned) { 2910 if (Ordered) { 2911 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize, 2912 IVSigned); 2913 } 2914 }; 2915 2916 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST, 2917 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB); 2918 OuterLoopArgs.IncExpr = S.getInc(); 2919 OuterLoopArgs.Init = S.getInit(); 2920 OuterLoopArgs.Cond = S.getCond(); 2921 OuterLoopArgs.NextLB = S.getNextLowerBound(); 2922 OuterLoopArgs.NextUB = S.getNextUpperBound(); 2923 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs, 2924 emitOMPLoopBodyWithStopPoint, CodeGenOrdered); 2925 } 2926 2927 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc, 2928 const unsigned IVSize, const bool IVSigned) {} 2929 2930 void CodeGenFunction::EmitOMPDistributeOuterLoop( 2931 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S, 2932 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs, 2933 const CodeGenLoopTy &CodeGenLoopContent) { 2934 2935 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2936 2937 // Emit outer loop. 2938 // Same behavior as a OMPForOuterLoop, except that schedule cannot be 2939 // dynamic 2940 // 2941 2942 const Expr *IVExpr = S.getIterationVariable(); 2943 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2944 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2945 2946 CGOpenMPRuntime::StaticRTInput StaticInit( 2947 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB, 2948 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk); 2949 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit); 2950 2951 // for combined 'distribute' and 'for' the increment expression of distribute 2952 // is stored in DistInc. For 'distribute' alone, it is in Inc. 2953 Expr *IncExpr; 2954 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())) 2955 IncExpr = S.getDistInc(); 2956 else 2957 IncExpr = S.getInc(); 2958 2959 // this routine is shared by 'omp distribute parallel for' and 2960 // 'omp distribute': select the right EUB expression depending on the 2961 // directive 2962 OMPLoopArguments OuterLoopArgs; 2963 OuterLoopArgs.LB = LoopArgs.LB; 2964 OuterLoopArgs.UB = LoopArgs.UB; 2965 OuterLoopArgs.ST = LoopArgs.ST; 2966 OuterLoopArgs.IL = LoopArgs.IL; 2967 OuterLoopArgs.Chunk = LoopArgs.Chunk; 2968 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2969 ? S.getCombinedEnsureUpperBound() 2970 : S.getEnsureUpperBound(); 2971 OuterLoopArgs.IncExpr = IncExpr; 2972 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2973 ? S.getCombinedInit() 2974 : S.getInit(); 2975 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2976 ? S.getCombinedCond() 2977 : S.getCond(); 2978 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2979 ? S.getCombinedNextLowerBound() 2980 : S.getNextLowerBound(); 2981 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2982 ? S.getCombinedNextUpperBound() 2983 : S.getNextUpperBound(); 2984 2985 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S, 2986 LoopScope, OuterLoopArgs, CodeGenLoopContent, 2987 emitEmptyOrdered); 2988 } 2989 2990 static std::pair<LValue, LValue> 2991 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF, 2992 const OMPExecutableDirective &S) { 2993 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2994 LValue LB = 2995 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 2996 LValue UB = 2997 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 2998 2999 // When composing 'distribute' with 'for' (e.g. as in 'distribute 3000 // parallel for') we need to use the 'distribute' 3001 // chunk lower and upper bounds rather than the whole loop iteration 3002 // space. These are parameters to the outlined function for 'parallel' 3003 // and we copy the bounds of the previous schedule into the 3004 // the current ones. 3005 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable()); 3006 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable()); 3007 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar( 3008 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc()); 3009 PrevLBVal = CGF.EmitScalarConversion( 3010 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(), 3011 LS.getIterationVariable()->getType(), 3012 LS.getPrevLowerBoundVariable()->getExprLoc()); 3013 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar( 3014 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc()); 3015 PrevUBVal = CGF.EmitScalarConversion( 3016 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(), 3017 LS.getIterationVariable()->getType(), 3018 LS.getPrevUpperBoundVariable()->getExprLoc()); 3019 3020 CGF.EmitStoreOfScalar(PrevLBVal, LB); 3021 CGF.EmitStoreOfScalar(PrevUBVal, UB); 3022 3023 return {LB, UB}; 3024 } 3025 3026 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then 3027 /// we need to use the LB and UB expressions generated by the worksharing 3028 /// code generation support, whereas in non combined situations we would 3029 /// just emit 0 and the LastIteration expression 3030 /// This function is necessary due to the difference of the LB and UB 3031 /// types for the RT emission routines for 'for_static_init' and 3032 /// 'for_dispatch_init' 3033 static std::pair<llvm::Value *, llvm::Value *> 3034 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF, 3035 const OMPExecutableDirective &S, 3036 Address LB, Address UB) { 3037 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 3038 const Expr *IVExpr = LS.getIterationVariable(); 3039 // when implementing a dynamic schedule for a 'for' combined with a 3040 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop 3041 // is not normalized as each team only executes its own assigned 3042 // distribute chunk 3043 QualType IteratorTy = IVExpr->getType(); 3044 llvm::Value *LBVal = 3045 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 3046 llvm::Value *UBVal = 3047 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 3048 return {LBVal, UBVal}; 3049 } 3050 3051 static void emitDistributeParallelForDistributeInnerBoundParams( 3052 CodeGenFunction &CGF, const OMPExecutableDirective &S, 3053 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) { 3054 const auto &Dir = cast<OMPLoopDirective>(S); 3055 LValue LB = 3056 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable())); 3057 llvm::Value *LBCast = 3058 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)), 3059 CGF.SizeTy, /*isSigned=*/false); 3060 CapturedVars.push_back(LBCast); 3061 LValue UB = 3062 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable())); 3063 3064 llvm::Value *UBCast = 3065 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)), 3066 CGF.SizeTy, /*isSigned=*/false); 3067 CapturedVars.push_back(UBCast); 3068 } 3069 3070 static void 3071 emitInnerParallelForWhenCombined(CodeGenFunction &CGF, 3072 const OMPLoopDirective &S, 3073 CodeGenFunction::JumpDest LoopExit) { 3074 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF, 3075 PrePostActionTy &Action) { 3076 Action.Enter(CGF); 3077 bool HasCancel = false; 3078 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 3079 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S)) 3080 HasCancel = D->hasCancel(); 3081 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S)) 3082 HasCancel = D->hasCancel(); 3083 else if (const auto *D = 3084 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S)) 3085 HasCancel = D->hasCancel(); 3086 } 3087 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 3088 HasCancel); 3089 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(), 3090 emitDistributeParallelForInnerBounds, 3091 emitDistributeParallelForDispatchBounds); 3092 }; 3093 3094 emitCommonOMPParallelDirective( 3095 CGF, S, 3096 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for, 3097 CGInlinedWorksharingLoop, 3098 emitDistributeParallelForDistributeInnerBoundParams); 3099 } 3100 3101 void CodeGenFunction::EmitOMPDistributeParallelForDirective( 3102 const OMPDistributeParallelForDirective &S) { 3103 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3104 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 3105 S.getDistInc()); 3106 }; 3107 OMPLexicalScope Scope(*this, S, OMPD_parallel); 3108 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 3109 } 3110 3111 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective( 3112 const OMPDistributeParallelForSimdDirective &S) { 3113 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3114 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 3115 S.getDistInc()); 3116 }; 3117 OMPLexicalScope Scope(*this, S, OMPD_parallel); 3118 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 3119 } 3120 3121 void CodeGenFunction::EmitOMPDistributeSimdDirective( 3122 const OMPDistributeSimdDirective &S) { 3123 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3124 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 3125 }; 3126 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3127 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 3128 } 3129 3130 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction( 3131 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) { 3132 // Emit SPMD target parallel for region as a standalone region. 3133 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3134 emitOMPSimdRegion(CGF, S, Action); 3135 }; 3136 llvm::Function *Fn; 3137 llvm::Constant *Addr; 3138 // Emit target region as a standalone region. 3139 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 3140 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 3141 assert(Fn && Addr && "Target device function emission failed."); 3142 } 3143 3144 void CodeGenFunction::EmitOMPTargetSimdDirective( 3145 const OMPTargetSimdDirective &S) { 3146 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3147 emitOMPSimdRegion(CGF, S, Action); 3148 }; 3149 emitCommonOMPTargetDirective(*this, S, CodeGen); 3150 } 3151 3152 namespace { 3153 struct ScheduleKindModifiersTy { 3154 OpenMPScheduleClauseKind Kind; 3155 OpenMPScheduleClauseModifier M1; 3156 OpenMPScheduleClauseModifier M2; 3157 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind, 3158 OpenMPScheduleClauseModifier M1, 3159 OpenMPScheduleClauseModifier M2) 3160 : Kind(Kind), M1(M1), M2(M2) {} 3161 }; 3162 } // namespace 3163 3164 bool CodeGenFunction::EmitOMPWorksharingLoop( 3165 const OMPLoopDirective &S, Expr *EUB, 3166 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 3167 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 3168 // Emit the loop iteration variable. 3169 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 3170 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 3171 EmitVarDecl(*IVDecl); 3172 3173 // Emit the iterations count variable. 3174 // If it is not a variable, Sema decided to calculate iterations count on each 3175 // iteration (e.g., it is foldable into a constant). 3176 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 3177 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 3178 // Emit calculation of the iterations count. 3179 EmitIgnoredExpr(S.getCalcLastIteration()); 3180 } 3181 3182 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 3183 3184 bool HasLastprivateClause; 3185 // Check pre-condition. 3186 { 3187 OMPLoopScope PreInitScope(*this, S); 3188 // Skip the entire loop if we don't meet the precondition. 3189 // If the condition constant folds and can be elided, avoid emitting the 3190 // whole loop. 3191 bool CondConstant; 3192 llvm::BasicBlock *ContBlock = nullptr; 3193 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 3194 if (!CondConstant) 3195 return false; 3196 } else { 3197 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 3198 ContBlock = createBasicBlock("omp.precond.end"); 3199 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 3200 getProfileCount(&S)); 3201 EmitBlock(ThenBlock); 3202 incrementProfileCounter(&S); 3203 } 3204 3205 RunCleanupsScope DoacrossCleanupScope(*this); 3206 bool Ordered = false; 3207 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) { 3208 if (OrderedClause->getNumForLoops()) 3209 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations()); 3210 else 3211 Ordered = true; 3212 } 3213 3214 llvm::DenseSet<const Expr *> EmittedFinals; 3215 emitAlignedClause(*this, S); 3216 bool HasLinears = EmitOMPLinearClauseInit(S); 3217 // Emit helper vars inits. 3218 3219 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S); 3220 LValue LB = Bounds.first; 3221 LValue UB = Bounds.second; 3222 LValue ST = 3223 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 3224 LValue IL = 3225 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 3226 3227 // Emit 'then' code. 3228 { 3229 OMPPrivateScope LoopScope(*this); 3230 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) { 3231 // Emit implicit barrier to synchronize threads and avoid data races on 3232 // initialization of firstprivate variables and post-update of 3233 // lastprivate variables. 3234 CGM.getOpenMPRuntime().emitBarrierCall( 3235 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3236 /*ForceSimpleCall=*/true); 3237 } 3238 EmitOMPPrivateClause(S, LoopScope); 3239 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 3240 *this, S, EmitLValue(S.getIterationVariable())); 3241 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 3242 EmitOMPReductionClauseInit(S, LoopScope); 3243 EmitOMPPrivateLoopCounters(S, LoopScope); 3244 EmitOMPLinearClause(S, LoopScope); 3245 (void)LoopScope.Privatize(); 3246 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3247 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 3248 3249 // Detect the loop schedule kind and chunk. 3250 const Expr *ChunkExpr = nullptr; 3251 OpenMPScheduleTy ScheduleKind; 3252 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) { 3253 ScheduleKind.Schedule = C->getScheduleKind(); 3254 ScheduleKind.M1 = C->getFirstScheduleModifier(); 3255 ScheduleKind.M2 = C->getSecondScheduleModifier(); 3256 ChunkExpr = C->getChunkSize(); 3257 } else { 3258 // Default behaviour for schedule clause. 3259 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk( 3260 *this, S, ScheduleKind.Schedule, ChunkExpr); 3261 } 3262 bool HasChunkSizeOne = false; 3263 llvm::Value *Chunk = nullptr; 3264 if (ChunkExpr) { 3265 Chunk = EmitScalarExpr(ChunkExpr); 3266 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(), 3267 S.getIterationVariable()->getType(), 3268 S.getBeginLoc()); 3269 Expr::EvalResult Result; 3270 if (ChunkExpr->EvaluateAsInt(Result, getContext())) { 3271 llvm::APSInt EvaluatedChunk = Result.Val.getInt(); 3272 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1); 3273 } 3274 } 3275 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 3276 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 3277 // OpenMP 4.5, 2.7.1 Loop Construct, Description. 3278 // If the static schedule kind is specified or if the ordered clause is 3279 // specified, and if no monotonic modifier is specified, the effect will 3280 // be as if the monotonic modifier was specified. 3281 bool StaticChunkedOne = 3282 RT.isStaticChunked(ScheduleKind.Schedule, 3283 /* Chunked */ Chunk != nullptr) && 3284 HasChunkSizeOne && 3285 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 3286 bool IsMonotonic = 3287 Ordered || 3288 (ScheduleKind.Schedule == OMPC_SCHEDULE_static && 3289 !(ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 3290 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)) || 3291 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic || 3292 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic; 3293 if ((RT.isStaticNonchunked(ScheduleKind.Schedule, 3294 /* Chunked */ Chunk != nullptr) || 3295 StaticChunkedOne) && 3296 !Ordered) { 3297 JumpDest LoopExit = 3298 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 3299 emitCommonSimdLoop( 3300 *this, S, 3301 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3302 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 3303 CGF.EmitOMPSimdInit(S); 3304 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) { 3305 if (C->getKind() == OMPC_ORDER_concurrent) 3306 CGF.LoopStack.setParallel(/*Enable=*/true); 3307 } 3308 }, 3309 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk, 3310 &S, ScheduleKind, LoopExit, 3311 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 3312 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 3313 // When no chunk_size is specified, the iteration space is divided 3314 // into chunks that are approximately equal in size, and at most 3315 // one chunk is distributed to each thread. Note that the size of 3316 // the chunks is unspecified in this case. 3317 CGOpenMPRuntime::StaticRTInput StaticInit( 3318 IVSize, IVSigned, Ordered, IL.getAddress(CGF), 3319 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF), 3320 StaticChunkedOne ? Chunk : nullptr); 3321 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 3322 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, 3323 StaticInit); 3324 // UB = min(UB, GlobalUB); 3325 if (!StaticChunkedOne) 3326 CGF.EmitIgnoredExpr(S.getEnsureUpperBound()); 3327 // IV = LB; 3328 CGF.EmitIgnoredExpr(S.getInit()); 3329 // For unchunked static schedule generate: 3330 // 3331 // while (idx <= UB) { 3332 // BODY; 3333 // ++idx; 3334 // } 3335 // 3336 // For static schedule with chunk one: 3337 // 3338 // while (IV <= PrevUB) { 3339 // BODY; 3340 // IV += ST; 3341 // } 3342 CGF.EmitOMPInnerLoop( 3343 S, LoopScope.requiresCleanups(), 3344 StaticChunkedOne ? S.getCombinedParForInDistCond() 3345 : S.getCond(), 3346 StaticChunkedOne ? S.getDistInc() : S.getInc(), 3347 [&S, LoopExit](CodeGenFunction &CGF) { 3348 emitOMPLoopBodyWithStopPoint(CGF, S, LoopExit); 3349 }, 3350 [](CodeGenFunction &) {}); 3351 }); 3352 EmitBlock(LoopExit.getBlock()); 3353 // Tell the runtime we are done. 3354 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3355 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3356 S.getDirectiveKind()); 3357 }; 3358 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 3359 } else { 3360 // Emit the outer loop, which requests its work chunk [LB..UB] from 3361 // runtime and runs the inner loop to process it. 3362 const OMPLoopArguments LoopArguments( 3363 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 3364 IL.getAddress(*this), Chunk, EUB); 3365 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered, 3366 LoopArguments, CGDispatchBounds); 3367 } 3368 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 3369 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 3370 return CGF.Builder.CreateIsNotNull( 3371 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3372 }); 3373 } 3374 EmitOMPReductionClauseFinal( 3375 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind()) 3376 ? /*Parallel and Simd*/ OMPD_parallel_for_simd 3377 : /*Parallel only*/ OMPD_parallel); 3378 // Emit post-update of the reduction variables if IsLastIter != 0. 3379 emitPostUpdateForReductionClause( 3380 *this, S, [IL, &S](CodeGenFunction &CGF) { 3381 return CGF.Builder.CreateIsNotNull( 3382 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3383 }); 3384 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3385 if (HasLastprivateClause) 3386 EmitOMPLastprivateClauseFinal( 3387 S, isOpenMPSimdDirective(S.getDirectiveKind()), 3388 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 3389 } 3390 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) { 3391 return CGF.Builder.CreateIsNotNull( 3392 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3393 }); 3394 DoacrossCleanupScope.ForceCleanup(); 3395 // We're now done with the loop, so jump to the continuation block. 3396 if (ContBlock) { 3397 EmitBranch(ContBlock); 3398 EmitBlock(ContBlock, /*IsFinished=*/true); 3399 } 3400 } 3401 return HasLastprivateClause; 3402 } 3403 3404 /// The following two functions generate expressions for the loop lower 3405 /// and upper bounds in case of static and dynamic (dispatch) schedule 3406 /// of the associated 'for' or 'distribute' loop. 3407 static std::pair<LValue, LValue> 3408 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3409 const auto &LS = cast<OMPLoopDirective>(S); 3410 LValue LB = 3411 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 3412 LValue UB = 3413 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 3414 return {LB, UB}; 3415 } 3416 3417 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not 3418 /// consider the lower and upper bound expressions generated by the 3419 /// worksharing loop support, but we use 0 and the iteration space size as 3420 /// constants 3421 static std::pair<llvm::Value *, llvm::Value *> 3422 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, 3423 Address LB, Address UB) { 3424 const auto &LS = cast<OMPLoopDirective>(S); 3425 const Expr *IVExpr = LS.getIterationVariable(); 3426 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType()); 3427 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0); 3428 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration()); 3429 return {LBVal, UBVal}; 3430 } 3431 3432 /// Emits internal temp array declarations for the directive with inscan 3433 /// reductions. 3434 /// The code is the following: 3435 /// \code 3436 /// size num_iters = <num_iters>; 3437 /// <type> buffer[num_iters]; 3438 /// \endcode 3439 static void emitScanBasedDirectiveDecls( 3440 CodeGenFunction &CGF, const OMPLoopDirective &S, 3441 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen) { 3442 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast( 3443 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false); 3444 SmallVector<const Expr *, 4> Shareds; 3445 SmallVector<const Expr *, 4> Privates; 3446 SmallVector<const Expr *, 4> ReductionOps; 3447 SmallVector<const Expr *, 4> CopyArrayTemps; 3448 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3449 assert(C->getModifier() == OMPC_REDUCTION_inscan && 3450 "Only inscan reductions are expected."); 3451 Shareds.append(C->varlist_begin(), C->varlist_end()); 3452 Privates.append(C->privates().begin(), C->privates().end()); 3453 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 3454 CopyArrayTemps.append(C->copy_array_temps().begin(), 3455 C->copy_array_temps().end()); 3456 } 3457 { 3458 // Emit buffers for each reduction variables. 3459 // ReductionCodeGen is required to emit correctly the code for array 3460 // reductions. 3461 ReductionCodeGen RedCG(Shareds, Shareds, Privates, ReductionOps); 3462 unsigned Count = 0; 3463 auto *ITA = CopyArrayTemps.begin(); 3464 for (const Expr *IRef : Privates) { 3465 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 3466 // Emit variably modified arrays, used for arrays/array sections 3467 // reductions. 3468 if (PrivateVD->getType()->isVariablyModifiedType()) { 3469 RedCG.emitSharedOrigLValue(CGF, Count); 3470 RedCG.emitAggregateType(CGF, Count); 3471 } 3472 CodeGenFunction::OpaqueValueMapping DimMapping( 3473 CGF, 3474 cast<OpaqueValueExpr>( 3475 cast<VariableArrayType>((*ITA)->getType()->getAsArrayTypeUnsafe()) 3476 ->getSizeExpr()), 3477 RValue::get(OMPScanNumIterations)); 3478 // Emit temp buffer. 3479 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(*ITA)->getDecl())); 3480 ++ITA; 3481 ++Count; 3482 } 3483 } 3484 } 3485 3486 /// Emits the code for the directive with inscan reductions. 3487 /// The code is the following: 3488 /// \code 3489 /// #pragma omp ... 3490 /// for (i: 0..<num_iters>) { 3491 /// <input phase>; 3492 /// buffer[i] = red; 3493 /// } 3494 /// #pragma omp master // in parallel region 3495 /// for (int k = 0; k != ceil(log2(num_iters)); ++k) 3496 /// for (size cnt = last_iter; cnt >= pow(2, k); --k) 3497 /// buffer[i] op= buffer[i-pow(2,k)]; 3498 /// #pragma omp barrier // in parallel region 3499 /// #pragma omp ... 3500 /// for (0..<num_iters>) { 3501 /// red = InclusiveScan ? buffer[i] : buffer[i-1]; 3502 /// <scan phase>; 3503 /// } 3504 /// \endcode 3505 static void emitScanBasedDirective( 3506 CodeGenFunction &CGF, const OMPLoopDirective &S, 3507 llvm::function_ref<llvm::Value *(CodeGenFunction &)> NumIteratorsGen, 3508 llvm::function_ref<void(CodeGenFunction &)> FirstGen, 3509 llvm::function_ref<void(CodeGenFunction &)> SecondGen) { 3510 llvm::Value *OMPScanNumIterations = CGF.Builder.CreateIntCast( 3511 NumIteratorsGen(CGF), CGF.SizeTy, /*isSigned=*/false); 3512 SmallVector<const Expr *, 4> Privates; 3513 SmallVector<const Expr *, 4> ReductionOps; 3514 SmallVector<const Expr *, 4> LHSs; 3515 SmallVector<const Expr *, 4> RHSs; 3516 SmallVector<const Expr *, 4> CopyArrayElems; 3517 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3518 assert(C->getModifier() == OMPC_REDUCTION_inscan && 3519 "Only inscan reductions are expected."); 3520 Privates.append(C->privates().begin(), C->privates().end()); 3521 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 3522 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 3523 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 3524 CopyArrayElems.append(C->copy_array_elems().begin(), 3525 C->copy_array_elems().end()); 3526 } 3527 CodeGenFunction::ParentLoopDirectiveForScanRegion ScanRegion(CGF, S); 3528 { 3529 // Emit loop with input phase: 3530 // #pragma omp ... 3531 // for (i: 0..<num_iters>) { 3532 // <input phase>; 3533 // buffer[i] = red; 3534 // } 3535 CGF.OMPFirstScanLoop = true; 3536 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 3537 FirstGen(CGF); 3538 } 3539 // #pragma omp barrier // in parallel region 3540 auto &&CodeGen = [&S, OMPScanNumIterations, &LHSs, &RHSs, &CopyArrayElems, 3541 &ReductionOps, 3542 &Privates](CodeGenFunction &CGF, PrePostActionTy &Action) { 3543 Action.Enter(CGF); 3544 // Emit prefix reduction: 3545 // #pragma omp master // in parallel region 3546 // for (int k = 0; k <= ceil(log2(n)); ++k) 3547 llvm::BasicBlock *InputBB = CGF.Builder.GetInsertBlock(); 3548 llvm::BasicBlock *LoopBB = CGF.createBasicBlock("omp.outer.log.scan.body"); 3549 llvm::BasicBlock *ExitBB = CGF.createBasicBlock("omp.outer.log.scan.exit"); 3550 llvm::Function *F = 3551 CGF.CGM.getIntrinsic(llvm::Intrinsic::log2, CGF.DoubleTy); 3552 llvm::Value *Arg = 3553 CGF.Builder.CreateUIToFP(OMPScanNumIterations, CGF.DoubleTy); 3554 llvm::Value *LogVal = CGF.EmitNounwindRuntimeCall(F, Arg); 3555 F = CGF.CGM.getIntrinsic(llvm::Intrinsic::ceil, CGF.DoubleTy); 3556 LogVal = CGF.EmitNounwindRuntimeCall(F, LogVal); 3557 LogVal = CGF.Builder.CreateFPToUI(LogVal, CGF.IntTy); 3558 llvm::Value *NMin1 = CGF.Builder.CreateNUWSub( 3559 OMPScanNumIterations, llvm::ConstantInt::get(CGF.SizeTy, 1)); 3560 auto DL = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getBeginLoc()); 3561 CGF.EmitBlock(LoopBB); 3562 auto *Counter = CGF.Builder.CreatePHI(CGF.IntTy, 2); 3563 // size pow2k = 1; 3564 auto *Pow2K = CGF.Builder.CreatePHI(CGF.SizeTy, 2); 3565 Counter->addIncoming(llvm::ConstantInt::get(CGF.IntTy, 0), InputBB); 3566 Pow2K->addIncoming(llvm::ConstantInt::get(CGF.SizeTy, 1), InputBB); 3567 // for (size i = n - 1; i >= 2 ^ k; --i) 3568 // tmp[i] op= tmp[i-pow2k]; 3569 llvm::BasicBlock *InnerLoopBB = 3570 CGF.createBasicBlock("omp.inner.log.scan.body"); 3571 llvm::BasicBlock *InnerExitBB = 3572 CGF.createBasicBlock("omp.inner.log.scan.exit"); 3573 llvm::Value *CmpI = CGF.Builder.CreateICmpUGE(NMin1, Pow2K); 3574 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB); 3575 CGF.EmitBlock(InnerLoopBB); 3576 auto *IVal = CGF.Builder.CreatePHI(CGF.SizeTy, 2); 3577 IVal->addIncoming(NMin1, LoopBB); 3578 { 3579 CodeGenFunction::OMPPrivateScope PrivScope(CGF); 3580 auto *ILHS = LHSs.begin(); 3581 auto *IRHS = RHSs.begin(); 3582 for (const Expr *CopyArrayElem : CopyArrayElems) { 3583 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 3584 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 3585 Address LHSAddr = Address::invalid(); 3586 { 3587 CodeGenFunction::OpaqueValueMapping IdxMapping( 3588 CGF, 3589 cast<OpaqueValueExpr>( 3590 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 3591 RValue::get(IVal)); 3592 LHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF); 3593 } 3594 PrivScope.addPrivate(LHSVD, LHSAddr); 3595 Address RHSAddr = Address::invalid(); 3596 { 3597 llvm::Value *OffsetIVal = CGF.Builder.CreateNUWSub(IVal, Pow2K); 3598 CodeGenFunction::OpaqueValueMapping IdxMapping( 3599 CGF, 3600 cast<OpaqueValueExpr>( 3601 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 3602 RValue::get(OffsetIVal)); 3603 RHSAddr = CGF.EmitLValue(CopyArrayElem).getAddress(CGF); 3604 } 3605 PrivScope.addPrivate(RHSVD, RHSAddr); 3606 ++ILHS; 3607 ++IRHS; 3608 } 3609 PrivScope.Privatize(); 3610 CGF.CGM.getOpenMPRuntime().emitReduction( 3611 CGF, S.getEndLoc(), Privates, LHSs, RHSs, ReductionOps, 3612 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_unknown}); 3613 } 3614 llvm::Value *NextIVal = 3615 CGF.Builder.CreateNUWSub(IVal, llvm::ConstantInt::get(CGF.SizeTy, 1)); 3616 IVal->addIncoming(NextIVal, CGF.Builder.GetInsertBlock()); 3617 CmpI = CGF.Builder.CreateICmpUGE(NextIVal, Pow2K); 3618 CGF.Builder.CreateCondBr(CmpI, InnerLoopBB, InnerExitBB); 3619 CGF.EmitBlock(InnerExitBB); 3620 llvm::Value *Next = 3621 CGF.Builder.CreateNUWAdd(Counter, llvm::ConstantInt::get(CGF.IntTy, 1)); 3622 Counter->addIncoming(Next, CGF.Builder.GetInsertBlock()); 3623 // pow2k <<= 1; 3624 llvm::Value *NextPow2K = 3625 CGF.Builder.CreateShl(Pow2K, 1, "", /*HasNUW=*/true); 3626 Pow2K->addIncoming(NextPow2K, CGF.Builder.GetInsertBlock()); 3627 llvm::Value *Cmp = CGF.Builder.CreateICmpNE(Next, LogVal); 3628 CGF.Builder.CreateCondBr(Cmp, LoopBB, ExitBB); 3629 auto DL1 = ApplyDebugLocation::CreateDefaultArtificial(CGF, S.getEndLoc()); 3630 CGF.EmitBlock(ExitBB); 3631 }; 3632 if (isOpenMPParallelDirective(S.getDirectiveKind())) { 3633 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 3634 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3635 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3636 /*ForceSimpleCall=*/true); 3637 } else { 3638 RegionCodeGenTy RCG(CodeGen); 3639 RCG(CGF); 3640 } 3641 3642 CGF.OMPFirstScanLoop = false; 3643 SecondGen(CGF); 3644 } 3645 3646 static bool emitWorksharingDirective(CodeGenFunction &CGF, 3647 const OMPLoopDirective &S, 3648 bool HasCancel) { 3649 bool HasLastprivates; 3650 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), 3651 [](const OMPReductionClause *C) { 3652 return C->getModifier() == OMPC_REDUCTION_inscan; 3653 })) { 3654 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) { 3655 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 3656 OMPLoopScope LoopScope(CGF, S); 3657 return CGF.EmitScalarExpr(S.getNumIterations()); 3658 }; 3659 const auto &&FirstGen = [&S, HasCancel](CodeGenFunction &CGF) { 3660 CodeGenFunction::OMPCancelStackRAII CancelRegion( 3661 CGF, S.getDirectiveKind(), HasCancel); 3662 (void)CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3663 emitForLoopBounds, 3664 emitDispatchForLoopBounds); 3665 // Emit an implicit barrier at the end. 3666 CGF.CGM.getOpenMPRuntime().emitBarrierCall(CGF, S.getBeginLoc(), 3667 OMPD_for); 3668 }; 3669 const auto &&SecondGen = [&S, HasCancel, 3670 &HasLastprivates](CodeGenFunction &CGF) { 3671 CodeGenFunction::OMPCancelStackRAII CancelRegion( 3672 CGF, S.getDirectiveKind(), HasCancel); 3673 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3674 emitForLoopBounds, 3675 emitDispatchForLoopBounds); 3676 }; 3677 if (!isOpenMPParallelDirective(S.getDirectiveKind())) 3678 emitScanBasedDirectiveDecls(CGF, S, NumIteratorsGen); 3679 emitScanBasedDirective(CGF, S, NumIteratorsGen, FirstGen, SecondGen); 3680 } else { 3681 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 3682 HasCancel); 3683 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 3684 emitForLoopBounds, 3685 emitDispatchForLoopBounds); 3686 } 3687 return HasLastprivates; 3688 } 3689 3690 static bool isSupportedByOpenMPIRBuilder(const OMPForDirective &S) { 3691 if (S.hasCancel()) 3692 return false; 3693 for (OMPClause *C : S.clauses()) { 3694 if (isa<OMPNowaitClause>(C)) 3695 continue; 3696 3697 if (auto *SC = dyn_cast<OMPScheduleClause>(C)) { 3698 if (SC->getFirstScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown) 3699 return false; 3700 if (SC->getSecondScheduleModifier() != OMPC_SCHEDULE_MODIFIER_unknown) 3701 return false; 3702 switch (SC->getScheduleKind()) { 3703 case OMPC_SCHEDULE_auto: 3704 case OMPC_SCHEDULE_dynamic: 3705 case OMPC_SCHEDULE_runtime: 3706 case OMPC_SCHEDULE_guided: 3707 case OMPC_SCHEDULE_static: 3708 continue; 3709 case OMPC_SCHEDULE_unknown: 3710 return false; 3711 } 3712 } 3713 3714 return false; 3715 } 3716 3717 return true; 3718 } 3719 3720 static llvm::omp::ScheduleKind 3721 convertClauseKindToSchedKind(OpenMPScheduleClauseKind ScheduleClauseKind) { 3722 switch (ScheduleClauseKind) { 3723 case OMPC_SCHEDULE_unknown: 3724 return llvm::omp::OMP_SCHEDULE_Default; 3725 case OMPC_SCHEDULE_auto: 3726 return llvm::omp::OMP_SCHEDULE_Auto; 3727 case OMPC_SCHEDULE_dynamic: 3728 return llvm::omp::OMP_SCHEDULE_Dynamic; 3729 case OMPC_SCHEDULE_guided: 3730 return llvm::omp::OMP_SCHEDULE_Guided; 3731 case OMPC_SCHEDULE_runtime: 3732 return llvm::omp::OMP_SCHEDULE_Runtime; 3733 case OMPC_SCHEDULE_static: 3734 return llvm::omp::OMP_SCHEDULE_Static; 3735 } 3736 llvm_unreachable("Unhandled schedule kind"); 3737 } 3738 3739 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 3740 bool HasLastprivates = false; 3741 bool UseOMPIRBuilder = 3742 CGM.getLangOpts().OpenMPIRBuilder && isSupportedByOpenMPIRBuilder(S); 3743 auto &&CodeGen = [this, &S, &HasLastprivates, 3744 UseOMPIRBuilder](CodeGenFunction &CGF, PrePostActionTy &) { 3745 // Use the OpenMPIRBuilder if enabled. 3746 if (UseOMPIRBuilder) { 3747 bool NeedsBarrier = !S.getSingleClause<OMPNowaitClause>(); 3748 3749 llvm::omp::ScheduleKind SchedKind = llvm::omp::OMP_SCHEDULE_Default; 3750 llvm::Value *ChunkSize = nullptr; 3751 if (auto *SchedClause = S.getSingleClause<OMPScheduleClause>()) { 3752 SchedKind = 3753 convertClauseKindToSchedKind(SchedClause->getScheduleKind()); 3754 if (const Expr *ChunkSizeExpr = SchedClause->getChunkSize()) 3755 ChunkSize = EmitScalarExpr(ChunkSizeExpr); 3756 } 3757 3758 // Emit the associated statement and get its loop representation. 3759 const Stmt *Inner = S.getRawStmt(); 3760 llvm::CanonicalLoopInfo *CLI = 3761 EmitOMPCollapsedCanonicalLoopNest(Inner, 1); 3762 3763 llvm::OpenMPIRBuilder &OMPBuilder = 3764 CGM.getOpenMPRuntime().getOMPBuilder(); 3765 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 3766 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 3767 OMPBuilder.applyWorkshareLoop( 3768 Builder.getCurrentDebugLocation(), CLI, AllocaIP, NeedsBarrier, 3769 SchedKind, ChunkSize, /*HasSimdModifier=*/false, 3770 /*HasMonotonicModifier=*/false, /*HasNonmonotonicModifier=*/false, 3771 /*HasOrderedClause=*/false); 3772 return; 3773 } 3774 3775 HasLastprivates = emitWorksharingDirective(CGF, S, S.hasCancel()); 3776 }; 3777 { 3778 auto LPCRegion = 3779 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3780 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3781 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen, 3782 S.hasCancel()); 3783 } 3784 3785 if (!UseOMPIRBuilder) { 3786 // Emit an implicit barrier at the end. 3787 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 3788 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 3789 } 3790 // Check for outer lastprivate conditional update. 3791 checkForLastprivateConditionalUpdate(*this, S); 3792 } 3793 3794 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) { 3795 bool HasLastprivates = false; 3796 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 3797 PrePostActionTy &) { 3798 HasLastprivates = emitWorksharingDirective(CGF, S, /*HasCancel=*/false); 3799 }; 3800 { 3801 auto LPCRegion = 3802 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3803 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3804 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 3805 } 3806 3807 // Emit an implicit barrier at the end. 3808 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 3809 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 3810 // Check for outer lastprivate conditional update. 3811 checkForLastprivateConditionalUpdate(*this, S); 3812 } 3813 3814 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 3815 const Twine &Name, 3816 llvm::Value *Init = nullptr) { 3817 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 3818 if (Init) 3819 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true); 3820 return LVal; 3821 } 3822 3823 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) { 3824 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt(); 3825 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt); 3826 bool HasLastprivates = false; 3827 auto &&CodeGen = [&S, CapturedStmt, CS, 3828 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) { 3829 const ASTContext &C = CGF.getContext(); 3830 QualType KmpInt32Ty = 3831 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 3832 // Emit helper vars inits. 3833 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 3834 CGF.Builder.getInt32(0)); 3835 llvm::ConstantInt *GlobalUBVal = CS != nullptr 3836 ? CGF.Builder.getInt32(CS->size() - 1) 3837 : CGF.Builder.getInt32(0); 3838 LValue UB = 3839 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 3840 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 3841 CGF.Builder.getInt32(1)); 3842 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 3843 CGF.Builder.getInt32(0)); 3844 // Loop counter. 3845 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 3846 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 3847 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 3848 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 3849 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 3850 // Generate condition for loop. 3851 BinaryOperator *Cond = BinaryOperator::Create( 3852 C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_PRValue, OK_Ordinary, 3853 S.getBeginLoc(), FPOptionsOverride()); 3854 // Increment for loop counter. 3855 UnaryOperator *Inc = UnaryOperator::Create( 3856 C, &IVRefExpr, UO_PreInc, KmpInt32Ty, VK_PRValue, OK_Ordinary, 3857 S.getBeginLoc(), true, FPOptionsOverride()); 3858 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) { 3859 // Iterate through all sections and emit a switch construct: 3860 // switch (IV) { 3861 // case 0: 3862 // <SectionStmt[0]>; 3863 // break; 3864 // ... 3865 // case <NumSection> - 1: 3866 // <SectionStmt[<NumSection> - 1]>; 3867 // break; 3868 // } 3869 // .omp.sections.exit: 3870 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 3871 llvm::SwitchInst *SwitchStmt = 3872 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()), 3873 ExitBB, CS == nullptr ? 1 : CS->size()); 3874 if (CS) { 3875 unsigned CaseNumber = 0; 3876 for (const Stmt *SubStmt : CS->children()) { 3877 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 3878 CGF.EmitBlock(CaseBB); 3879 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 3880 CGF.EmitStmt(SubStmt); 3881 CGF.EmitBranch(ExitBB); 3882 ++CaseNumber; 3883 } 3884 } else { 3885 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case"); 3886 CGF.EmitBlock(CaseBB); 3887 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB); 3888 CGF.EmitStmt(CapturedStmt); 3889 CGF.EmitBranch(ExitBB); 3890 } 3891 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 3892 }; 3893 3894 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 3895 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 3896 // Emit implicit barrier to synchronize threads and avoid data races on 3897 // initialization of firstprivate variables and post-update of lastprivate 3898 // variables. 3899 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3900 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3901 /*ForceSimpleCall=*/true); 3902 } 3903 CGF.EmitOMPPrivateClause(S, LoopScope); 3904 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV); 3905 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 3906 CGF.EmitOMPReductionClauseInit(S, LoopScope); 3907 (void)LoopScope.Privatize(); 3908 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3909 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 3910 3911 // Emit static non-chunked loop. 3912 OpenMPScheduleTy ScheduleKind; 3913 ScheduleKind.Schedule = OMPC_SCHEDULE_static; 3914 CGOpenMPRuntime::StaticRTInput StaticInit( 3915 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF), 3916 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF)); 3917 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 3918 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit); 3919 // UB = min(UB, GlobalUB); 3920 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc()); 3921 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect( 3922 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 3923 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 3924 // IV = LB; 3925 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV); 3926 // while (idx <= UB) { BODY; ++idx; } 3927 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, Inc, BodyGen, 3928 [](CodeGenFunction &) {}); 3929 // Tell the runtime we are done. 3930 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3931 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3932 S.getDirectiveKind()); 3933 }; 3934 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen); 3935 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3936 // Emit post-update of the reduction variables if IsLastIter != 0. 3937 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) { 3938 return CGF.Builder.CreateIsNotNull( 3939 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3940 }); 3941 3942 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3943 if (HasLastprivates) 3944 CGF.EmitOMPLastprivateClauseFinal( 3945 S, /*NoFinals=*/false, 3946 CGF.Builder.CreateIsNotNull( 3947 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()))); 3948 }; 3949 3950 bool HasCancel = false; 3951 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S)) 3952 HasCancel = OSD->hasCancel(); 3953 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S)) 3954 HasCancel = OPSD->hasCancel(); 3955 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel); 3956 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen, 3957 HasCancel); 3958 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 3959 // clause. Otherwise the barrier will be generated by the codegen for the 3960 // directive. 3961 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) { 3962 // Emit implicit barrier to synchronize threads and avoid data races on 3963 // initialization of firstprivate variables. 3964 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3965 OMPD_unknown); 3966 } 3967 } 3968 3969 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 3970 if (CGM.getLangOpts().OpenMPIRBuilder) { 3971 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 3972 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3973 using BodyGenCallbackTy = llvm::OpenMPIRBuilder::StorableBodyGenCallbackTy; 3974 3975 auto FiniCB = [this](InsertPointTy IP) { 3976 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3977 }; 3978 3979 const CapturedStmt *ICS = S.getInnermostCapturedStmt(); 3980 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt(); 3981 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt); 3982 llvm::SmallVector<BodyGenCallbackTy, 4> SectionCBVector; 3983 if (CS) { 3984 for (const Stmt *SubStmt : CS->children()) { 3985 auto SectionCB = [this, SubStmt](InsertPointTy AllocaIP, 3986 InsertPointTy CodeGenIP, 3987 llvm::BasicBlock &FiniBB) { 3988 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, 3989 FiniBB); 3990 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SubStmt, CodeGenIP, 3991 FiniBB); 3992 }; 3993 SectionCBVector.push_back(SectionCB); 3994 } 3995 } else { 3996 auto SectionCB = [this, CapturedStmt](InsertPointTy AllocaIP, 3997 InsertPointTy CodeGenIP, 3998 llvm::BasicBlock &FiniBB) { 3999 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 4000 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CapturedStmt, CodeGenIP, 4001 FiniBB); 4002 }; 4003 SectionCBVector.push_back(SectionCB); 4004 } 4005 4006 // Privatization callback that performs appropriate action for 4007 // shared/private/firstprivate/lastprivate/copyin/... variables. 4008 // 4009 // TODO: This defaults to shared right now. 4010 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 4011 llvm::Value &, llvm::Value &Val, llvm::Value *&ReplVal) { 4012 // The next line is appropriate only for variables (Val) with the 4013 // data-sharing attribute "shared". 4014 ReplVal = &Val; 4015 4016 return CodeGenIP; 4017 }; 4018 4019 CGCapturedStmtInfo CGSI(*ICS, CR_OpenMP); 4020 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 4021 llvm::OpenMPIRBuilder::InsertPointTy AllocaIP( 4022 AllocaInsertPt->getParent(), AllocaInsertPt->getIterator()); 4023 Builder.restoreIP(OMPBuilder.createSections( 4024 Builder, AllocaIP, SectionCBVector, PrivCB, FiniCB, S.hasCancel(), 4025 S.getSingleClause<OMPNowaitClause>())); 4026 return; 4027 } 4028 { 4029 auto LPCRegion = 4030 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4031 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4032 EmitSections(S); 4033 } 4034 // Emit an implicit barrier at the end. 4035 if (!S.getSingleClause<OMPNowaitClause>()) { 4036 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 4037 OMPD_sections); 4038 } 4039 // Check for outer lastprivate conditional update. 4040 checkForLastprivateConditionalUpdate(*this, S); 4041 } 4042 4043 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 4044 if (CGM.getLangOpts().OpenMPIRBuilder) { 4045 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 4046 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 4047 4048 const Stmt *SectionRegionBodyStmt = S.getAssociatedStmt(); 4049 auto FiniCB = [this](InsertPointTy IP) { 4050 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 4051 }; 4052 4053 auto BodyGenCB = [SectionRegionBodyStmt, this](InsertPointTy AllocaIP, 4054 InsertPointTy CodeGenIP, 4055 llvm::BasicBlock &FiniBB) { 4056 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 4057 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, SectionRegionBodyStmt, 4058 CodeGenIP, FiniBB); 4059 }; 4060 4061 LexicalScope Scope(*this, S.getSourceRange()); 4062 EmitStopPoint(&S); 4063 Builder.restoreIP(OMPBuilder.createSection(Builder, BodyGenCB, FiniCB)); 4064 4065 return; 4066 } 4067 LexicalScope Scope(*this, S.getSourceRange()); 4068 EmitStopPoint(&S); 4069 EmitStmt(S.getAssociatedStmt()); 4070 } 4071 4072 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 4073 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 4074 llvm::SmallVector<const Expr *, 8> DestExprs; 4075 llvm::SmallVector<const Expr *, 8> SrcExprs; 4076 llvm::SmallVector<const Expr *, 8> AssignmentOps; 4077 // Check if there are any 'copyprivate' clauses associated with this 4078 // 'single' construct. 4079 // Build a list of copyprivate variables along with helper expressions 4080 // (<source>, <destination>, <destination>=<source> expressions) 4081 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) { 4082 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 4083 DestExprs.append(C->destination_exprs().begin(), 4084 C->destination_exprs().end()); 4085 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 4086 AssignmentOps.append(C->assignment_ops().begin(), 4087 C->assignment_ops().end()); 4088 } 4089 // Emit code for 'single' region along with 'copyprivate' clauses 4090 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4091 Action.Enter(CGF); 4092 OMPPrivateScope SingleScope(CGF); 4093 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope); 4094 CGF.EmitOMPPrivateClause(S, SingleScope); 4095 (void)SingleScope.Privatize(); 4096 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 4097 }; 4098 { 4099 auto LPCRegion = 4100 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4101 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4102 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(), 4103 CopyprivateVars, DestExprs, 4104 SrcExprs, AssignmentOps); 4105 } 4106 // Emit an implicit barrier at the end (to avoid data race on firstprivate 4107 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 4108 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) { 4109 CGM.getOpenMPRuntime().emitBarrierCall( 4110 *this, S.getBeginLoc(), 4111 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single); 4112 } 4113 // Check for outer lastprivate conditional update. 4114 checkForLastprivateConditionalUpdate(*this, S); 4115 } 4116 4117 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 4118 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4119 Action.Enter(CGF); 4120 CGF.EmitStmt(S.getRawStmt()); 4121 }; 4122 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 4123 } 4124 4125 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 4126 if (CGM.getLangOpts().OpenMPIRBuilder) { 4127 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 4128 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 4129 4130 const Stmt *MasterRegionBodyStmt = S.getAssociatedStmt(); 4131 4132 auto FiniCB = [this](InsertPointTy IP) { 4133 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 4134 }; 4135 4136 auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP, 4137 InsertPointTy CodeGenIP, 4138 llvm::BasicBlock &FiniBB) { 4139 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 4140 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt, 4141 CodeGenIP, FiniBB); 4142 }; 4143 4144 LexicalScope Scope(*this, S.getSourceRange()); 4145 EmitStopPoint(&S); 4146 Builder.restoreIP(OMPBuilder.createMaster(Builder, BodyGenCB, FiniCB)); 4147 4148 return; 4149 } 4150 LexicalScope Scope(*this, S.getSourceRange()); 4151 EmitStopPoint(&S); 4152 emitMaster(*this, S); 4153 } 4154 4155 static void emitMasked(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 4156 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4157 Action.Enter(CGF); 4158 CGF.EmitStmt(S.getRawStmt()); 4159 }; 4160 Expr *Filter = nullptr; 4161 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>()) 4162 Filter = FilterClause->getThreadID(); 4163 CGF.CGM.getOpenMPRuntime().emitMaskedRegion(CGF, CodeGen, S.getBeginLoc(), 4164 Filter); 4165 } 4166 4167 void CodeGenFunction::EmitOMPMaskedDirective(const OMPMaskedDirective &S) { 4168 if (CGM.getLangOpts().OpenMPIRBuilder) { 4169 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 4170 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 4171 4172 const Stmt *MaskedRegionBodyStmt = S.getAssociatedStmt(); 4173 const Expr *Filter = nullptr; 4174 if (const auto *FilterClause = S.getSingleClause<OMPFilterClause>()) 4175 Filter = FilterClause->getThreadID(); 4176 llvm::Value *FilterVal = Filter 4177 ? EmitScalarExpr(Filter, CGM.Int32Ty) 4178 : llvm::ConstantInt::get(CGM.Int32Ty, /*V=*/0); 4179 4180 auto FiniCB = [this](InsertPointTy IP) { 4181 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 4182 }; 4183 4184 auto BodyGenCB = [MaskedRegionBodyStmt, this](InsertPointTy AllocaIP, 4185 InsertPointTy CodeGenIP, 4186 llvm::BasicBlock &FiniBB) { 4187 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 4188 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MaskedRegionBodyStmt, 4189 CodeGenIP, FiniBB); 4190 }; 4191 4192 LexicalScope Scope(*this, S.getSourceRange()); 4193 EmitStopPoint(&S); 4194 Builder.restoreIP( 4195 OMPBuilder.createMasked(Builder, BodyGenCB, FiniCB, FilterVal)); 4196 4197 return; 4198 } 4199 LexicalScope Scope(*this, S.getSourceRange()); 4200 EmitStopPoint(&S); 4201 emitMasked(*this, S); 4202 } 4203 4204 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 4205 if (CGM.getLangOpts().OpenMPIRBuilder) { 4206 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 4207 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 4208 4209 const Stmt *CriticalRegionBodyStmt = S.getAssociatedStmt(); 4210 const Expr *Hint = nullptr; 4211 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 4212 Hint = HintClause->getHint(); 4213 4214 // TODO: This is slightly different from what's currently being done in 4215 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything 4216 // about typing is final. 4217 llvm::Value *HintInst = nullptr; 4218 if (Hint) 4219 HintInst = 4220 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false); 4221 4222 auto FiniCB = [this](InsertPointTy IP) { 4223 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 4224 }; 4225 4226 auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP, 4227 InsertPointTy CodeGenIP, 4228 llvm::BasicBlock &FiniBB) { 4229 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 4230 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt, 4231 CodeGenIP, FiniBB); 4232 }; 4233 4234 LexicalScope Scope(*this, S.getSourceRange()); 4235 EmitStopPoint(&S); 4236 Builder.restoreIP(OMPBuilder.createCritical( 4237 Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(), 4238 HintInst)); 4239 4240 return; 4241 } 4242 4243 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4244 Action.Enter(CGF); 4245 CGF.EmitStmt(S.getAssociatedStmt()); 4246 }; 4247 const Expr *Hint = nullptr; 4248 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 4249 Hint = HintClause->getHint(); 4250 LexicalScope Scope(*this, S.getSourceRange()); 4251 EmitStopPoint(&S); 4252 CGM.getOpenMPRuntime().emitCriticalRegion(*this, 4253 S.getDirectiveName().getAsString(), 4254 CodeGen, S.getBeginLoc(), Hint); 4255 } 4256 4257 void CodeGenFunction::EmitOMPParallelForDirective( 4258 const OMPParallelForDirective &S) { 4259 // Emit directive as a combined directive that consists of two implicit 4260 // directives: 'parallel' with 'for' directive. 4261 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4262 Action.Enter(CGF); 4263 (void)emitWorksharingDirective(CGF, S, S.hasCancel()); 4264 }; 4265 { 4266 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), 4267 [](const OMPReductionClause *C) { 4268 return C->getModifier() == OMPC_REDUCTION_inscan; 4269 })) { 4270 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) { 4271 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 4272 CGCapturedStmtInfo CGSI(CR_OpenMP); 4273 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI); 4274 OMPLoopScope LoopScope(CGF, S); 4275 return CGF.EmitScalarExpr(S.getNumIterations()); 4276 }; 4277 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen); 4278 } 4279 auto LPCRegion = 4280 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4281 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen, 4282 emitEmptyBoundParameters); 4283 } 4284 // Check for outer lastprivate conditional update. 4285 checkForLastprivateConditionalUpdate(*this, S); 4286 } 4287 4288 void CodeGenFunction::EmitOMPParallelForSimdDirective( 4289 const OMPParallelForSimdDirective &S) { 4290 // Emit directive as a combined directive that consists of two implicit 4291 // directives: 'parallel' with 'for' directive. 4292 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4293 Action.Enter(CGF); 4294 (void)emitWorksharingDirective(CGF, S, /*HasCancel=*/false); 4295 }; 4296 { 4297 if (llvm::any_of(S.getClausesOfKind<OMPReductionClause>(), 4298 [](const OMPReductionClause *C) { 4299 return C->getModifier() == OMPC_REDUCTION_inscan; 4300 })) { 4301 const auto &&NumIteratorsGen = [&S](CodeGenFunction &CGF) { 4302 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 4303 CGCapturedStmtInfo CGSI(CR_OpenMP); 4304 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(CGF, &CGSI); 4305 OMPLoopScope LoopScope(CGF, S); 4306 return CGF.EmitScalarExpr(S.getNumIterations()); 4307 }; 4308 emitScanBasedDirectiveDecls(*this, S, NumIteratorsGen); 4309 } 4310 auto LPCRegion = 4311 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4312 emitCommonOMPParallelDirective(*this, S, OMPD_for_simd, CodeGen, 4313 emitEmptyBoundParameters); 4314 } 4315 // Check for outer lastprivate conditional update. 4316 checkForLastprivateConditionalUpdate(*this, S); 4317 } 4318 4319 void CodeGenFunction::EmitOMPParallelMasterDirective( 4320 const OMPParallelMasterDirective &S) { 4321 // Emit directive as a combined directive that consists of two implicit 4322 // directives: 'parallel' with 'master' directive. 4323 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4324 Action.Enter(CGF); 4325 OMPPrivateScope PrivateScope(CGF); 4326 bool Copyins = CGF.EmitOMPCopyinClause(S); 4327 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4328 if (Copyins) { 4329 // Emit implicit barrier to synchronize threads and avoid data races on 4330 // propagation master's thread values of threadprivate variables to local 4331 // instances of that variables of all other implicit threads. 4332 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 4333 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 4334 /*ForceSimpleCall=*/true); 4335 } 4336 CGF.EmitOMPPrivateClause(S, PrivateScope); 4337 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4338 (void)PrivateScope.Privatize(); 4339 emitMaster(CGF, S); 4340 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 4341 }; 4342 { 4343 auto LPCRegion = 4344 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4345 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen, 4346 emitEmptyBoundParameters); 4347 emitPostUpdateForReductionClause(*this, S, 4348 [](CodeGenFunction &) { return nullptr; }); 4349 } 4350 // Check for outer lastprivate conditional update. 4351 checkForLastprivateConditionalUpdate(*this, S); 4352 } 4353 4354 void CodeGenFunction::EmitOMPParallelSectionsDirective( 4355 const OMPParallelSectionsDirective &S) { 4356 // Emit directive as a combined directive that consists of two implicit 4357 // directives: 'parallel' with 'sections' directive. 4358 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4359 Action.Enter(CGF); 4360 CGF.EmitSections(S); 4361 }; 4362 { 4363 auto LPCRegion = 4364 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4365 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen, 4366 emitEmptyBoundParameters); 4367 } 4368 // Check for outer lastprivate conditional update. 4369 checkForLastprivateConditionalUpdate(*this, S); 4370 } 4371 4372 namespace { 4373 /// Get the list of variables declared in the context of the untied tasks. 4374 class CheckVarsEscapingUntiedTaskDeclContext final 4375 : public ConstStmtVisitor<CheckVarsEscapingUntiedTaskDeclContext> { 4376 llvm::SmallVector<const VarDecl *, 4> PrivateDecls; 4377 4378 public: 4379 explicit CheckVarsEscapingUntiedTaskDeclContext() = default; 4380 virtual ~CheckVarsEscapingUntiedTaskDeclContext() = default; 4381 void VisitDeclStmt(const DeclStmt *S) { 4382 if (!S) 4383 return; 4384 // Need to privatize only local vars, static locals can be processed as is. 4385 for (const Decl *D : S->decls()) { 4386 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) 4387 if (VD->hasLocalStorage()) 4388 PrivateDecls.push_back(VD); 4389 } 4390 } 4391 void VisitOMPExecutableDirective(const OMPExecutableDirective *) {} 4392 void VisitCapturedStmt(const CapturedStmt *) {} 4393 void VisitLambdaExpr(const LambdaExpr *) {} 4394 void VisitBlockExpr(const BlockExpr *) {} 4395 void VisitStmt(const Stmt *S) { 4396 if (!S) 4397 return; 4398 for (const Stmt *Child : S->children()) 4399 if (Child) 4400 Visit(Child); 4401 } 4402 4403 /// Swaps list of vars with the provided one. 4404 ArrayRef<const VarDecl *> getPrivateDecls() const { return PrivateDecls; } 4405 }; 4406 } // anonymous namespace 4407 4408 void CodeGenFunction::EmitOMPTaskBasedDirective( 4409 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, 4410 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, 4411 OMPTaskDataTy &Data) { 4412 // Emit outlined function for task construct. 4413 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion); 4414 auto I = CS->getCapturedDecl()->param_begin(); 4415 auto PartId = std::next(I); 4416 auto TaskT = std::next(I, 4); 4417 // Check if the task is final 4418 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) { 4419 // If the condition constant folds and can be elided, try to avoid emitting 4420 // the condition and the dead arm of the if/else. 4421 const Expr *Cond = Clause->getCondition(); 4422 bool CondConstant; 4423 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 4424 Data.Final.setInt(CondConstant); 4425 else 4426 Data.Final.setPointer(EvaluateExprAsBool(Cond)); 4427 } else { 4428 // By default the task is not final. 4429 Data.Final.setInt(/*IntVal=*/false); 4430 } 4431 // Check if the task has 'priority' clause. 4432 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) { 4433 const Expr *Prio = Clause->getPriority(); 4434 Data.Priority.setInt(/*IntVal=*/true); 4435 Data.Priority.setPointer(EmitScalarConversion( 4436 EmitScalarExpr(Prio), Prio->getType(), 4437 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), 4438 Prio->getExprLoc())); 4439 } 4440 // The first function argument for tasks is a thread id, the second one is a 4441 // part id (0 for tied tasks, >=0 for untied task). 4442 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 4443 // Get list of private variables. 4444 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 4445 auto IRef = C->varlist_begin(); 4446 for (const Expr *IInit : C->private_copies()) { 4447 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4448 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4449 Data.PrivateVars.push_back(*IRef); 4450 Data.PrivateCopies.push_back(IInit); 4451 } 4452 ++IRef; 4453 } 4454 } 4455 EmittedAsPrivate.clear(); 4456 // Get list of firstprivate variables. 4457 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 4458 auto IRef = C->varlist_begin(); 4459 auto IElemInitRef = C->inits().begin(); 4460 for (const Expr *IInit : C->private_copies()) { 4461 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4462 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4463 Data.FirstprivateVars.push_back(*IRef); 4464 Data.FirstprivateCopies.push_back(IInit); 4465 Data.FirstprivateInits.push_back(*IElemInitRef); 4466 } 4467 ++IRef; 4468 ++IElemInitRef; 4469 } 4470 } 4471 // Get list of lastprivate variables (for taskloops). 4472 llvm::MapVector<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs; 4473 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 4474 auto IRef = C->varlist_begin(); 4475 auto ID = C->destination_exprs().begin(); 4476 for (const Expr *IInit : C->private_copies()) { 4477 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 4478 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 4479 Data.LastprivateVars.push_back(*IRef); 4480 Data.LastprivateCopies.push_back(IInit); 4481 } 4482 LastprivateDstsOrigs.insert( 4483 std::make_pair(cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()), 4484 cast<DeclRefExpr>(*IRef))); 4485 ++IRef; 4486 ++ID; 4487 } 4488 } 4489 SmallVector<const Expr *, 4> LHSs; 4490 SmallVector<const Expr *, 4> RHSs; 4491 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 4492 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end()); 4493 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 4494 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 4495 Data.ReductionOps.append(C->reduction_ops().begin(), 4496 C->reduction_ops().end()); 4497 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 4498 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 4499 } 4500 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit( 4501 *this, S.getBeginLoc(), LHSs, RHSs, Data); 4502 // Build list of dependences. 4503 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 4504 OMPTaskDataTy::DependData &DD = 4505 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 4506 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 4507 } 4508 // Get list of local vars for untied tasks. 4509 if (!Data.Tied) { 4510 CheckVarsEscapingUntiedTaskDeclContext Checker; 4511 Checker.Visit(S.getInnermostCapturedStmt()->getCapturedStmt()); 4512 Data.PrivateLocals.append(Checker.getPrivateDecls().begin(), 4513 Checker.getPrivateDecls().end()); 4514 } 4515 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs, 4516 CapturedRegion](CodeGenFunction &CGF, 4517 PrePostActionTy &Action) { 4518 llvm::MapVector<CanonicalDeclPtr<const VarDecl>, 4519 std::pair<Address, Address>> 4520 UntiedLocalVars; 4521 // Set proper addresses for generated private copies. 4522 OMPPrivateScope Scope(CGF); 4523 // Generate debug info for variables present in shared clause. 4524 if (auto *DI = CGF.getDebugInfo()) { 4525 llvm::SmallDenseMap<const VarDecl *, FieldDecl *> CaptureFields = 4526 CGF.CapturedStmtInfo->getCaptureFields(); 4527 llvm::Value *ContextValue = CGF.CapturedStmtInfo->getContextValue(); 4528 if (CaptureFields.size() && ContextValue) { 4529 unsigned CharWidth = CGF.getContext().getCharWidth(); 4530 // The shared variables are packed together as members of structure. 4531 // So the address of each shared variable can be computed by adding 4532 // offset of it (within record) to the base address of record. For each 4533 // shared variable, debug intrinsic llvm.dbg.declare is generated with 4534 // appropriate expressions (DIExpression). 4535 // Ex: 4536 // %12 = load %struct.anon*, %struct.anon** %__context.addr.i 4537 // call void @llvm.dbg.declare(metadata %struct.anon* %12, 4538 // metadata !svar1, 4539 // metadata !DIExpression(DW_OP_deref)) 4540 // call void @llvm.dbg.declare(metadata %struct.anon* %12, 4541 // metadata !svar2, 4542 // metadata !DIExpression(DW_OP_plus_uconst, 8, DW_OP_deref)) 4543 for (auto It = CaptureFields.begin(); It != CaptureFields.end(); ++It) { 4544 const VarDecl *SharedVar = It->first; 4545 RecordDecl *CaptureRecord = It->second->getParent(); 4546 const ASTRecordLayout &Layout = 4547 CGF.getContext().getASTRecordLayout(CaptureRecord); 4548 unsigned Offset = 4549 Layout.getFieldOffset(It->second->getFieldIndex()) / CharWidth; 4550 if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo()) 4551 (void)DI->EmitDeclareOfAutoVariable(SharedVar, ContextValue, 4552 CGF.Builder, false); 4553 llvm::Instruction &Last = CGF.Builder.GetInsertBlock()->back(); 4554 // Get the call dbg.declare instruction we just created and update 4555 // its DIExpression to add offset to base address. 4556 if (auto DDI = dyn_cast<llvm::DbgVariableIntrinsic>(&Last)) { 4557 SmallVector<uint64_t, 8> Ops; 4558 // Add offset to the base address if non zero. 4559 if (Offset) { 4560 Ops.push_back(llvm::dwarf::DW_OP_plus_uconst); 4561 Ops.push_back(Offset); 4562 } 4563 Ops.push_back(llvm::dwarf::DW_OP_deref); 4564 auto &Ctx = DDI->getContext(); 4565 llvm::DIExpression *DIExpr = llvm::DIExpression::get(Ctx, Ops); 4566 Last.setOperand(2, llvm::MetadataAsValue::get(Ctx, DIExpr)); 4567 } 4568 } 4569 } 4570 } 4571 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> FirstprivatePtrs; 4572 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() || 4573 !Data.LastprivateVars.empty() || !Data.PrivateLocals.empty()) { 4574 enum { PrivatesParam = 2, CopyFnParam = 3 }; 4575 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 4576 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 4577 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 4578 CS->getCapturedDecl()->getParam(PrivatesParam))); 4579 // Map privates. 4580 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 4581 llvm::SmallVector<llvm::Value *, 16> CallArgs; 4582 llvm::SmallVector<llvm::Type *, 4> ParamTypes; 4583 CallArgs.push_back(PrivatesPtr); 4584 ParamTypes.push_back(PrivatesPtr->getType()); 4585 for (const Expr *E : Data.PrivateVars) { 4586 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4587 Address PrivatePtr = CGF.CreateMemTemp( 4588 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr"); 4589 PrivatePtrs.emplace_back(VD, PrivatePtr); 4590 CallArgs.push_back(PrivatePtr.getPointer()); 4591 ParamTypes.push_back(PrivatePtr.getType()); 4592 } 4593 for (const Expr *E : Data.FirstprivateVars) { 4594 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4595 Address PrivatePtr = 4596 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4597 ".firstpriv.ptr.addr"); 4598 PrivatePtrs.emplace_back(VD, PrivatePtr); 4599 FirstprivatePtrs.emplace_back(VD, PrivatePtr); 4600 CallArgs.push_back(PrivatePtr.getPointer()); 4601 ParamTypes.push_back(PrivatePtr.getType()); 4602 } 4603 for (const Expr *E : Data.LastprivateVars) { 4604 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4605 Address PrivatePtr = 4606 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4607 ".lastpriv.ptr.addr"); 4608 PrivatePtrs.emplace_back(VD, PrivatePtr); 4609 CallArgs.push_back(PrivatePtr.getPointer()); 4610 ParamTypes.push_back(PrivatePtr.getType()); 4611 } 4612 for (const VarDecl *VD : Data.PrivateLocals) { 4613 QualType Ty = VD->getType().getNonReferenceType(); 4614 if (VD->getType()->isLValueReferenceType()) 4615 Ty = CGF.getContext().getPointerType(Ty); 4616 if (isAllocatableDecl(VD)) 4617 Ty = CGF.getContext().getPointerType(Ty); 4618 Address PrivatePtr = CGF.CreateMemTemp( 4619 CGF.getContext().getPointerType(Ty), ".local.ptr.addr"); 4620 auto Result = UntiedLocalVars.insert( 4621 std::make_pair(VD, std::make_pair(PrivatePtr, Address::invalid()))); 4622 // If key exists update in place. 4623 if (Result.second == false) 4624 *Result.first = std::make_pair( 4625 VD, std::make_pair(PrivatePtr, Address::invalid())); 4626 CallArgs.push_back(PrivatePtr.getPointer()); 4627 ParamTypes.push_back(PrivatePtr.getType()); 4628 } 4629 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(), 4630 ParamTypes, /*isVarArg=*/false); 4631 CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4632 CopyFn, CopyFnTy->getPointerTo()); 4633 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 4634 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 4635 for (const auto &Pair : LastprivateDstsOrigs) { 4636 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl()); 4637 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD), 4638 /*RefersToEnclosingVariableOrCapture=*/ 4639 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr, 4640 Pair.second->getType(), VK_LValue, 4641 Pair.second->getExprLoc()); 4642 Scope.addPrivate(Pair.first, CGF.EmitLValue(&DRE).getAddress(CGF)); 4643 } 4644 for (const auto &Pair : PrivatePtrs) { 4645 Address Replacement = Address( 4646 CGF.Builder.CreateLoad(Pair.second), 4647 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()), 4648 CGF.getContext().getDeclAlign(Pair.first)); 4649 Scope.addPrivate(Pair.first, Replacement); 4650 if (auto *DI = CGF.getDebugInfo()) 4651 if (CGF.CGM.getCodeGenOpts().hasReducedDebugInfo()) 4652 (void)DI->EmitDeclareOfAutoVariable( 4653 Pair.first, Pair.second.getPointer(), CGF.Builder, 4654 /*UsePointerValue*/ true); 4655 } 4656 // Adjust mapping for internal locals by mapping actual memory instead of 4657 // a pointer to this memory. 4658 for (auto &Pair : UntiedLocalVars) { 4659 QualType VDType = Pair.first->getType().getNonReferenceType(); 4660 if (isAllocatableDecl(Pair.first)) { 4661 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first); 4662 Address Replacement( 4663 Ptr, 4664 CGF.ConvertTypeForMem(CGF.getContext().getPointerType(VDType)), 4665 CGF.getPointerAlign()); 4666 Pair.second.first = Replacement; 4667 Ptr = CGF.Builder.CreateLoad(Replacement); 4668 Replacement = Address(Ptr, CGF.ConvertTypeForMem(VDType), 4669 CGF.getContext().getDeclAlign(Pair.first)); 4670 Pair.second.second = Replacement; 4671 } else { 4672 llvm::Value *Ptr = CGF.Builder.CreateLoad(Pair.second.first); 4673 Address Replacement(Ptr, CGF.ConvertTypeForMem(VDType), 4674 CGF.getContext().getDeclAlign(Pair.first)); 4675 Pair.second.first = Replacement; 4676 } 4677 } 4678 } 4679 if (Data.Reductions) { 4680 OMPPrivateScope FirstprivateScope(CGF); 4681 for (const auto &Pair : FirstprivatePtrs) { 4682 Address Replacement( 4683 CGF.Builder.CreateLoad(Pair.second), 4684 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()), 4685 CGF.getContext().getDeclAlign(Pair.first)); 4686 FirstprivateScope.addPrivate(Pair.first, Replacement); 4687 } 4688 (void)FirstprivateScope.Privatize(); 4689 OMPLexicalScope LexScope(CGF, S, CapturedRegion); 4690 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionVars, 4691 Data.ReductionCopies, Data.ReductionOps); 4692 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad( 4693 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9))); 4694 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) { 4695 RedCG.emitSharedOrigLValue(CGF, Cnt); 4696 RedCG.emitAggregateType(CGF, Cnt); 4697 // FIXME: This must removed once the runtime library is fixed. 4698 // Emit required threadprivate variables for 4699 // initializer/combiner/finalizer. 4700 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 4701 RedCG, Cnt); 4702 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 4703 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 4704 Replacement = 4705 Address(CGF.EmitScalarConversion( 4706 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 4707 CGF.getContext().getPointerType( 4708 Data.ReductionCopies[Cnt]->getType()), 4709 Data.ReductionCopies[Cnt]->getExprLoc()), 4710 CGF.ConvertTypeForMem(Data.ReductionCopies[Cnt]->getType()), 4711 Replacement.getAlignment()); 4712 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 4713 Scope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement); 4714 } 4715 } 4716 // Privatize all private variables except for in_reduction items. 4717 (void)Scope.Privatize(); 4718 SmallVector<const Expr *, 4> InRedVars; 4719 SmallVector<const Expr *, 4> InRedPrivs; 4720 SmallVector<const Expr *, 4> InRedOps; 4721 SmallVector<const Expr *, 4> TaskgroupDescriptors; 4722 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) { 4723 auto IPriv = C->privates().begin(); 4724 auto IRed = C->reduction_ops().begin(); 4725 auto ITD = C->taskgroup_descriptors().begin(); 4726 for (const Expr *Ref : C->varlists()) { 4727 InRedVars.emplace_back(Ref); 4728 InRedPrivs.emplace_back(*IPriv); 4729 InRedOps.emplace_back(*IRed); 4730 TaskgroupDescriptors.emplace_back(*ITD); 4731 std::advance(IPriv, 1); 4732 std::advance(IRed, 1); 4733 std::advance(ITD, 1); 4734 } 4735 } 4736 // Privatize in_reduction items here, because taskgroup descriptors must be 4737 // privatized earlier. 4738 OMPPrivateScope InRedScope(CGF); 4739 if (!InRedVars.empty()) { 4740 ReductionCodeGen RedCG(InRedVars, InRedVars, InRedPrivs, InRedOps); 4741 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) { 4742 RedCG.emitSharedOrigLValue(CGF, Cnt); 4743 RedCG.emitAggregateType(CGF, Cnt); 4744 // The taskgroup descriptor variable is always implicit firstprivate and 4745 // privatized already during processing of the firstprivates. 4746 // FIXME: This must removed once the runtime library is fixed. 4747 // Emit required threadprivate variables for 4748 // initializer/combiner/finalizer. 4749 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 4750 RedCG, Cnt); 4751 llvm::Value *ReductionsPtr; 4752 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) { 4753 ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr), 4754 TRExpr->getExprLoc()); 4755 } else { 4756 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 4757 } 4758 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 4759 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 4760 Replacement = Address( 4761 CGF.EmitScalarConversion( 4762 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 4763 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()), 4764 InRedPrivs[Cnt]->getExprLoc()), 4765 CGF.ConvertTypeForMem(InRedPrivs[Cnt]->getType()), 4766 Replacement.getAlignment()); 4767 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 4768 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), Replacement); 4769 } 4770 } 4771 (void)InRedScope.Privatize(); 4772 4773 CGOpenMPRuntime::UntiedTaskLocalDeclsRAII LocalVarsScope(CGF, 4774 UntiedLocalVars); 4775 Action.Enter(CGF); 4776 BodyGen(CGF); 4777 }; 4778 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 4779 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied, 4780 Data.NumberOfParts); 4781 OMPLexicalScope Scope(*this, S, llvm::None, 4782 !isOpenMPParallelDirective(S.getDirectiveKind()) && 4783 !isOpenMPSimdDirective(S.getDirectiveKind())); 4784 TaskGen(*this, OutlinedFn, Data); 4785 } 4786 4787 static ImplicitParamDecl * 4788 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, 4789 QualType Ty, CapturedDecl *CD, 4790 SourceLocation Loc) { 4791 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 4792 ImplicitParamDecl::Other); 4793 auto *OrigRef = DeclRefExpr::Create( 4794 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD, 4795 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 4796 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 4797 ImplicitParamDecl::Other); 4798 auto *PrivateRef = DeclRefExpr::Create( 4799 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD, 4800 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 4801 QualType ElemType = C.getBaseElementType(Ty); 4802 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType, 4803 ImplicitParamDecl::Other); 4804 auto *InitRef = DeclRefExpr::Create( 4805 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD, 4806 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue); 4807 PrivateVD->setInitStyle(VarDecl::CInit); 4808 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue, 4809 InitRef, /*BasePath=*/nullptr, 4810 VK_PRValue, FPOptionsOverride())); 4811 Data.FirstprivateVars.emplace_back(OrigRef); 4812 Data.FirstprivateCopies.emplace_back(PrivateRef); 4813 Data.FirstprivateInits.emplace_back(InitRef); 4814 return OrigVD; 4815 } 4816 4817 void CodeGenFunction::EmitOMPTargetTaskBasedDirective( 4818 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, 4819 OMPTargetDataInfo &InputInfo) { 4820 // Emit outlined function for task construct. 4821 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 4822 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 4823 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 4824 auto I = CS->getCapturedDecl()->param_begin(); 4825 auto PartId = std::next(I); 4826 auto TaskT = std::next(I, 4); 4827 OMPTaskDataTy Data; 4828 // The task is not final. 4829 Data.Final.setInt(/*IntVal=*/false); 4830 // Get list of firstprivate variables. 4831 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 4832 auto IRef = C->varlist_begin(); 4833 auto IElemInitRef = C->inits().begin(); 4834 for (auto *IInit : C->private_copies()) { 4835 Data.FirstprivateVars.push_back(*IRef); 4836 Data.FirstprivateCopies.push_back(IInit); 4837 Data.FirstprivateInits.push_back(*IElemInitRef); 4838 ++IRef; 4839 ++IElemInitRef; 4840 } 4841 } 4842 OMPPrivateScope TargetScope(*this); 4843 VarDecl *BPVD = nullptr; 4844 VarDecl *PVD = nullptr; 4845 VarDecl *SVD = nullptr; 4846 VarDecl *MVD = nullptr; 4847 if (InputInfo.NumberOfTargetItems > 0) { 4848 auto *CD = CapturedDecl::Create( 4849 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0); 4850 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems); 4851 QualType BaseAndPointerAndMapperType = getContext().getConstantArrayType( 4852 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal, 4853 /*IndexTypeQuals=*/0); 4854 BPVD = createImplicitFirstprivateForType( 4855 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4856 PVD = createImplicitFirstprivateForType( 4857 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4858 QualType SizesType = getContext().getConstantArrayType( 4859 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1), 4860 ArrSize, nullptr, ArrayType::Normal, 4861 /*IndexTypeQuals=*/0); 4862 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD, 4863 S.getBeginLoc()); 4864 TargetScope.addPrivate(BPVD, InputInfo.BasePointersArray); 4865 TargetScope.addPrivate(PVD, InputInfo.PointersArray); 4866 TargetScope.addPrivate(SVD, InputInfo.SizesArray); 4867 // If there is no user-defined mapper, the mapper array will be nullptr. In 4868 // this case, we don't need to privatize it. 4869 if (!isa_and_nonnull<llvm::ConstantPointerNull>( 4870 InputInfo.MappersArray.getPointer())) { 4871 MVD = createImplicitFirstprivateForType( 4872 getContext(), Data, BaseAndPointerAndMapperType, CD, S.getBeginLoc()); 4873 TargetScope.addPrivate(MVD, InputInfo.MappersArray); 4874 } 4875 } 4876 (void)TargetScope.Privatize(); 4877 // Build list of dependences. 4878 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 4879 OMPTaskDataTy::DependData &DD = 4880 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 4881 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 4882 } 4883 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, MVD, 4884 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) { 4885 // Set proper addresses for generated private copies. 4886 OMPPrivateScope Scope(CGF); 4887 if (!Data.FirstprivateVars.empty()) { 4888 enum { PrivatesParam = 2, CopyFnParam = 3 }; 4889 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 4890 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 4891 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 4892 CS->getCapturedDecl()->getParam(PrivatesParam))); 4893 // Map privates. 4894 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 4895 llvm::SmallVector<llvm::Value *, 16> CallArgs; 4896 llvm::SmallVector<llvm::Type *, 4> ParamTypes; 4897 CallArgs.push_back(PrivatesPtr); 4898 ParamTypes.push_back(PrivatesPtr->getType()); 4899 for (const Expr *E : Data.FirstprivateVars) { 4900 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 4901 Address PrivatePtr = 4902 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 4903 ".firstpriv.ptr.addr"); 4904 PrivatePtrs.emplace_back(VD, PrivatePtr); 4905 CallArgs.push_back(PrivatePtr.getPointer()); 4906 ParamTypes.push_back(PrivatePtr.getType()); 4907 } 4908 auto *CopyFnTy = llvm::FunctionType::get(CGF.Builder.getVoidTy(), 4909 ParamTypes, /*isVarArg=*/false); 4910 CopyFn = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast( 4911 CopyFn, CopyFnTy->getPointerTo()); 4912 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 4913 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 4914 for (const auto &Pair : PrivatePtrs) { 4915 Address Replacement( 4916 CGF.Builder.CreateLoad(Pair.second), 4917 CGF.ConvertTypeForMem(Pair.first->getType().getNonReferenceType()), 4918 CGF.getContext().getDeclAlign(Pair.first)); 4919 Scope.addPrivate(Pair.first, Replacement); 4920 } 4921 } 4922 // Privatize all private variables except for in_reduction items. 4923 (void)Scope.Privatize(); 4924 if (InputInfo.NumberOfTargetItems > 0) { 4925 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP( 4926 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0); 4927 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP( 4928 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0); 4929 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP( 4930 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0); 4931 // If MVD is nullptr, the mapper array is not privatized 4932 if (MVD) 4933 InputInfo.MappersArray = CGF.Builder.CreateConstArrayGEP( 4934 CGF.GetAddrOfLocalVar(MVD), /*Index=*/0); 4935 } 4936 4937 Action.Enter(CGF); 4938 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false); 4939 BodyGen(CGF); 4940 }; 4941 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 4942 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true, 4943 Data.NumberOfParts); 4944 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0); 4945 IntegerLiteral IfCond(getContext(), TrueOrFalse, 4946 getContext().getIntTypeForBitwidth(32, /*Signed=*/0), 4947 SourceLocation()); 4948 4949 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn, 4950 SharedsTy, CapturedStruct, &IfCond, Data); 4951 } 4952 4953 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 4954 // Emit outlined function for task construct. 4955 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 4956 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 4957 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 4958 const Expr *IfCond = nullptr; 4959 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 4960 if (C->getNameModifier() == OMPD_unknown || 4961 C->getNameModifier() == OMPD_task) { 4962 IfCond = C->getCondition(); 4963 break; 4964 } 4965 } 4966 4967 OMPTaskDataTy Data; 4968 // Check if we should emit tied or untied task. 4969 Data.Tied = !S.getSingleClause<OMPUntiedClause>(); 4970 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) { 4971 CGF.EmitStmt(CS->getCapturedStmt()); 4972 }; 4973 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 4974 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 4975 const OMPTaskDataTy &Data) { 4976 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn, 4977 SharedsTy, CapturedStruct, IfCond, 4978 Data); 4979 }; 4980 auto LPCRegion = 4981 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 4982 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data); 4983 } 4984 4985 void CodeGenFunction::EmitOMPTaskyieldDirective( 4986 const OMPTaskyieldDirective &S) { 4987 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc()); 4988 } 4989 4990 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 4991 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier); 4992 } 4993 4994 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 4995 OMPTaskDataTy Data; 4996 // Build list of dependences 4997 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 4998 OMPTaskDataTy::DependData &DD = 4999 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 5000 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 5001 } 5002 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc(), Data); 5003 } 5004 5005 void CodeGenFunction::EmitOMPTaskgroupDirective( 5006 const OMPTaskgroupDirective &S) { 5007 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5008 Action.Enter(CGF); 5009 if (const Expr *E = S.getReductionRef()) { 5010 SmallVector<const Expr *, 4> LHSs; 5011 SmallVector<const Expr *, 4> RHSs; 5012 OMPTaskDataTy Data; 5013 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) { 5014 Data.ReductionVars.append(C->varlist_begin(), C->varlist_end()); 5015 Data.ReductionOrigs.append(C->varlist_begin(), C->varlist_end()); 5016 Data.ReductionCopies.append(C->privates().begin(), C->privates().end()); 5017 Data.ReductionOps.append(C->reduction_ops().begin(), 5018 C->reduction_ops().end()); 5019 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 5020 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 5021 } 5022 llvm::Value *ReductionDesc = 5023 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(), 5024 LHSs, RHSs, Data); 5025 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 5026 CGF.EmitVarDecl(*VD); 5027 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD), 5028 /*Volatile=*/false, E->getType()); 5029 } 5030 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 5031 }; 5032 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5033 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc()); 5034 } 5035 5036 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 5037 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>() 5038 ? llvm::AtomicOrdering::NotAtomic 5039 : llvm::AtomicOrdering::AcquireRelease; 5040 CGM.getOpenMPRuntime().emitFlush( 5041 *this, 5042 [&S]() -> ArrayRef<const Expr *> { 5043 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) 5044 return llvm::makeArrayRef(FlushClause->varlist_begin(), 5045 FlushClause->varlist_end()); 5046 return llvm::None; 5047 }(), 5048 S.getBeginLoc(), AO); 5049 } 5050 5051 void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) { 5052 const auto *DO = S.getSingleClause<OMPDepobjClause>(); 5053 LValue DOLVal = EmitLValue(DO->getDepobj()); 5054 if (const auto *DC = S.getSingleClause<OMPDependClause>()) { 5055 OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(), 5056 DC->getModifier()); 5057 Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end()); 5058 Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause( 5059 *this, Dependencies, DC->getBeginLoc()); 5060 EmitStoreOfScalar(DepAddr.getPointer(), DOLVal); 5061 return; 5062 } 5063 if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) { 5064 CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc()); 5065 return; 5066 } 5067 if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) { 5068 CGM.getOpenMPRuntime().emitUpdateClause( 5069 *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc()); 5070 return; 5071 } 5072 } 5073 5074 void CodeGenFunction::EmitOMPScanDirective(const OMPScanDirective &S) { 5075 if (!OMPParentLoopDirectiveForScan) 5076 return; 5077 const OMPExecutableDirective &ParentDir = *OMPParentLoopDirectiveForScan; 5078 bool IsInclusive = S.hasClausesOfKind<OMPInclusiveClause>(); 5079 SmallVector<const Expr *, 4> Shareds; 5080 SmallVector<const Expr *, 4> Privates; 5081 SmallVector<const Expr *, 4> LHSs; 5082 SmallVector<const Expr *, 4> RHSs; 5083 SmallVector<const Expr *, 4> ReductionOps; 5084 SmallVector<const Expr *, 4> CopyOps; 5085 SmallVector<const Expr *, 4> CopyArrayTemps; 5086 SmallVector<const Expr *, 4> CopyArrayElems; 5087 for (const auto *C : ParentDir.getClausesOfKind<OMPReductionClause>()) { 5088 if (C->getModifier() != OMPC_REDUCTION_inscan) 5089 continue; 5090 Shareds.append(C->varlist_begin(), C->varlist_end()); 5091 Privates.append(C->privates().begin(), C->privates().end()); 5092 LHSs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 5093 RHSs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 5094 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 5095 CopyOps.append(C->copy_ops().begin(), C->copy_ops().end()); 5096 CopyArrayTemps.append(C->copy_array_temps().begin(), 5097 C->copy_array_temps().end()); 5098 CopyArrayElems.append(C->copy_array_elems().begin(), 5099 C->copy_array_elems().end()); 5100 } 5101 if (ParentDir.getDirectiveKind() == OMPD_simd || 5102 (getLangOpts().OpenMPSimd && 5103 isOpenMPSimdDirective(ParentDir.getDirectiveKind()))) { 5104 // For simd directive and simd-based directives in simd only mode, use the 5105 // following codegen: 5106 // int x = 0; 5107 // #pragma omp simd reduction(inscan, +: x) 5108 // for (..) { 5109 // <first part> 5110 // #pragma omp scan inclusive(x) 5111 // <second part> 5112 // } 5113 // is transformed to: 5114 // int x = 0; 5115 // for (..) { 5116 // int x_priv = 0; 5117 // <first part> 5118 // x = x_priv + x; 5119 // x_priv = x; 5120 // <second part> 5121 // } 5122 // and 5123 // int x = 0; 5124 // #pragma omp simd reduction(inscan, +: x) 5125 // for (..) { 5126 // <first part> 5127 // #pragma omp scan exclusive(x) 5128 // <second part> 5129 // } 5130 // to 5131 // int x = 0; 5132 // for (..) { 5133 // int x_priv = 0; 5134 // <second part> 5135 // int temp = x; 5136 // x = x_priv + x; 5137 // x_priv = temp; 5138 // <first part> 5139 // } 5140 llvm::BasicBlock *OMPScanReduce = createBasicBlock("omp.inscan.reduce"); 5141 EmitBranch(IsInclusive 5142 ? OMPScanReduce 5143 : BreakContinueStack.back().ContinueBlock.getBlock()); 5144 EmitBlock(OMPScanDispatch); 5145 { 5146 // New scope for correct construction/destruction of temp variables for 5147 // exclusive scan. 5148 LexicalScope Scope(*this, S.getSourceRange()); 5149 EmitBranch(IsInclusive ? OMPBeforeScanBlock : OMPAfterScanBlock); 5150 EmitBlock(OMPScanReduce); 5151 if (!IsInclusive) { 5152 // Create temp var and copy LHS value to this temp value. 5153 // TMP = LHS; 5154 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 5155 const Expr *PrivateExpr = Privates[I]; 5156 const Expr *TempExpr = CopyArrayTemps[I]; 5157 EmitAutoVarDecl( 5158 *cast<VarDecl>(cast<DeclRefExpr>(TempExpr)->getDecl())); 5159 LValue DestLVal = EmitLValue(TempExpr); 5160 LValue SrcLVal = EmitLValue(LHSs[I]); 5161 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 5162 SrcLVal.getAddress(*this), 5163 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 5164 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 5165 CopyOps[I]); 5166 } 5167 } 5168 CGM.getOpenMPRuntime().emitReduction( 5169 *this, ParentDir.getEndLoc(), Privates, LHSs, RHSs, ReductionOps, 5170 {/*WithNowait=*/true, /*SimpleReduction=*/true, OMPD_simd}); 5171 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 5172 const Expr *PrivateExpr = Privates[I]; 5173 LValue DestLVal; 5174 LValue SrcLVal; 5175 if (IsInclusive) { 5176 DestLVal = EmitLValue(RHSs[I]); 5177 SrcLVal = EmitLValue(LHSs[I]); 5178 } else { 5179 const Expr *TempExpr = CopyArrayTemps[I]; 5180 DestLVal = EmitLValue(RHSs[I]); 5181 SrcLVal = EmitLValue(TempExpr); 5182 } 5183 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 5184 SrcLVal.getAddress(*this), 5185 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 5186 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 5187 CopyOps[I]); 5188 } 5189 } 5190 EmitBranch(IsInclusive ? OMPAfterScanBlock : OMPBeforeScanBlock); 5191 OMPScanExitBlock = IsInclusive 5192 ? BreakContinueStack.back().ContinueBlock.getBlock() 5193 : OMPScanReduce; 5194 EmitBlock(OMPAfterScanBlock); 5195 return; 5196 } 5197 if (!IsInclusive) { 5198 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 5199 EmitBlock(OMPScanExitBlock); 5200 } 5201 if (OMPFirstScanLoop) { 5202 // Emit buffer[i] = red; at the end of the input phase. 5203 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir) 5204 .getIterationVariable() 5205 ->IgnoreParenImpCasts(); 5206 LValue IdxLVal = EmitLValue(IVExpr); 5207 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc()); 5208 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false); 5209 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 5210 const Expr *PrivateExpr = Privates[I]; 5211 const Expr *OrigExpr = Shareds[I]; 5212 const Expr *CopyArrayElem = CopyArrayElems[I]; 5213 OpaqueValueMapping IdxMapping( 5214 *this, 5215 cast<OpaqueValueExpr>( 5216 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 5217 RValue::get(IdxVal)); 5218 LValue DestLVal = EmitLValue(CopyArrayElem); 5219 LValue SrcLVal = EmitLValue(OrigExpr); 5220 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 5221 SrcLVal.getAddress(*this), 5222 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 5223 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 5224 CopyOps[I]); 5225 } 5226 } 5227 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 5228 if (IsInclusive) { 5229 EmitBlock(OMPScanExitBlock); 5230 EmitBranch(BreakContinueStack.back().ContinueBlock.getBlock()); 5231 } 5232 EmitBlock(OMPScanDispatch); 5233 if (!OMPFirstScanLoop) { 5234 // Emit red = buffer[i]; at the entrance to the scan phase. 5235 const auto *IVExpr = cast<OMPLoopDirective>(ParentDir) 5236 .getIterationVariable() 5237 ->IgnoreParenImpCasts(); 5238 LValue IdxLVal = EmitLValue(IVExpr); 5239 llvm::Value *IdxVal = EmitLoadOfScalar(IdxLVal, IVExpr->getExprLoc()); 5240 IdxVal = Builder.CreateIntCast(IdxVal, SizeTy, /*isSigned=*/false); 5241 llvm::BasicBlock *ExclusiveExitBB = nullptr; 5242 if (!IsInclusive) { 5243 llvm::BasicBlock *ContBB = createBasicBlock("omp.exclusive.dec"); 5244 ExclusiveExitBB = createBasicBlock("omp.exclusive.copy.exit"); 5245 llvm::Value *Cmp = Builder.CreateIsNull(IdxVal); 5246 Builder.CreateCondBr(Cmp, ExclusiveExitBB, ContBB); 5247 EmitBlock(ContBB); 5248 // Use idx - 1 iteration for exclusive scan. 5249 IdxVal = Builder.CreateNUWSub(IdxVal, llvm::ConstantInt::get(SizeTy, 1)); 5250 } 5251 for (unsigned I = 0, E = CopyArrayElems.size(); I < E; ++I) { 5252 const Expr *PrivateExpr = Privates[I]; 5253 const Expr *OrigExpr = Shareds[I]; 5254 const Expr *CopyArrayElem = CopyArrayElems[I]; 5255 OpaqueValueMapping IdxMapping( 5256 *this, 5257 cast<OpaqueValueExpr>( 5258 cast<ArraySubscriptExpr>(CopyArrayElem)->getIdx()), 5259 RValue::get(IdxVal)); 5260 LValue SrcLVal = EmitLValue(CopyArrayElem); 5261 LValue DestLVal = EmitLValue(OrigExpr); 5262 EmitOMPCopy(PrivateExpr->getType(), DestLVal.getAddress(*this), 5263 SrcLVal.getAddress(*this), 5264 cast<VarDecl>(cast<DeclRefExpr>(LHSs[I])->getDecl()), 5265 cast<VarDecl>(cast<DeclRefExpr>(RHSs[I])->getDecl()), 5266 CopyOps[I]); 5267 } 5268 if (!IsInclusive) { 5269 EmitBlock(ExclusiveExitBB); 5270 } 5271 } 5272 EmitBranch((OMPFirstScanLoop == IsInclusive) ? OMPBeforeScanBlock 5273 : OMPAfterScanBlock); 5274 EmitBlock(OMPAfterScanBlock); 5275 } 5276 5277 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S, 5278 const CodeGenLoopTy &CodeGenLoop, 5279 Expr *IncExpr) { 5280 // Emit the loop iteration variable. 5281 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 5282 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 5283 EmitVarDecl(*IVDecl); 5284 5285 // Emit the iterations count variable. 5286 // If it is not a variable, Sema decided to calculate iterations count on each 5287 // iteration (e.g., it is foldable into a constant). 5288 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 5289 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 5290 // Emit calculation of the iterations count. 5291 EmitIgnoredExpr(S.getCalcLastIteration()); 5292 } 5293 5294 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 5295 5296 bool HasLastprivateClause = false; 5297 // Check pre-condition. 5298 { 5299 OMPLoopScope PreInitScope(*this, S); 5300 // Skip the entire loop if we don't meet the precondition. 5301 // If the condition constant folds and can be elided, avoid emitting the 5302 // whole loop. 5303 bool CondConstant; 5304 llvm::BasicBlock *ContBlock = nullptr; 5305 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 5306 if (!CondConstant) 5307 return; 5308 } else { 5309 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 5310 ContBlock = createBasicBlock("omp.precond.end"); 5311 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 5312 getProfileCount(&S)); 5313 EmitBlock(ThenBlock); 5314 incrementProfileCounter(&S); 5315 } 5316 5317 emitAlignedClause(*this, S); 5318 // Emit 'then' code. 5319 { 5320 // Emit helper vars inits. 5321 5322 LValue LB = EmitOMPHelperVar( 5323 *this, cast<DeclRefExpr>( 5324 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5325 ? S.getCombinedLowerBoundVariable() 5326 : S.getLowerBoundVariable()))); 5327 LValue UB = EmitOMPHelperVar( 5328 *this, cast<DeclRefExpr>( 5329 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5330 ? S.getCombinedUpperBoundVariable() 5331 : S.getUpperBoundVariable()))); 5332 LValue ST = 5333 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 5334 LValue IL = 5335 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 5336 5337 OMPPrivateScope LoopScope(*this); 5338 if (EmitOMPFirstprivateClause(S, LoopScope)) { 5339 // Emit implicit barrier to synchronize threads and avoid data races 5340 // on initialization of firstprivate variables and post-update of 5341 // lastprivate variables. 5342 CGM.getOpenMPRuntime().emitBarrierCall( 5343 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 5344 /*ForceSimpleCall=*/true); 5345 } 5346 EmitOMPPrivateClause(S, LoopScope); 5347 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 5348 !isOpenMPParallelDirective(S.getDirectiveKind()) && 5349 !isOpenMPTeamsDirective(S.getDirectiveKind())) 5350 EmitOMPReductionClauseInit(S, LoopScope); 5351 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 5352 EmitOMPPrivateLoopCounters(S, LoopScope); 5353 (void)LoopScope.Privatize(); 5354 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 5355 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 5356 5357 // Detect the distribute schedule kind and chunk. 5358 llvm::Value *Chunk = nullptr; 5359 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown; 5360 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) { 5361 ScheduleKind = C->getDistScheduleKind(); 5362 if (const Expr *Ch = C->getChunkSize()) { 5363 Chunk = EmitScalarExpr(Ch); 5364 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 5365 S.getIterationVariable()->getType(), 5366 S.getBeginLoc()); 5367 } 5368 } else { 5369 // Default behaviour for dist_schedule clause. 5370 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk( 5371 *this, S, ScheduleKind, Chunk); 5372 } 5373 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 5374 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 5375 5376 // OpenMP [2.10.8, distribute Construct, Description] 5377 // If dist_schedule is specified, kind must be static. If specified, 5378 // iterations are divided into chunks of size chunk_size, chunks are 5379 // assigned to the teams of the league in a round-robin fashion in the 5380 // order of the team number. When no chunk_size is specified, the 5381 // iteration space is divided into chunks that are approximately equal 5382 // in size, and at most one chunk is distributed to each team of the 5383 // league. The size of the chunks is unspecified in this case. 5384 bool StaticChunked = 5385 RT.isStaticChunked(ScheduleKind, /* Chunked */ Chunk != nullptr) && 5386 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 5387 if (RT.isStaticNonchunked(ScheduleKind, 5388 /* Chunked */ Chunk != nullptr) || 5389 StaticChunked) { 5390 CGOpenMPRuntime::StaticRTInput StaticInit( 5391 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this), 5392 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 5393 StaticChunked ? Chunk : nullptr); 5394 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, 5395 StaticInit); 5396 JumpDest LoopExit = 5397 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 5398 // UB = min(UB, GlobalUB); 5399 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5400 ? S.getCombinedEnsureUpperBound() 5401 : S.getEnsureUpperBound()); 5402 // IV = LB; 5403 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5404 ? S.getCombinedInit() 5405 : S.getInit()); 5406 5407 const Expr *Cond = 5408 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 5409 ? S.getCombinedCond() 5410 : S.getCond(); 5411 5412 if (StaticChunked) 5413 Cond = S.getCombinedDistCond(); 5414 5415 // For static unchunked schedules generate: 5416 // 5417 // 1. For distribute alone, codegen 5418 // while (idx <= UB) { 5419 // BODY; 5420 // ++idx; 5421 // } 5422 // 5423 // 2. When combined with 'for' (e.g. as in 'distribute parallel for') 5424 // while (idx <= UB) { 5425 // <CodeGen rest of pragma>(LB, UB); 5426 // idx += ST; 5427 // } 5428 // 5429 // For static chunk one schedule generate: 5430 // 5431 // while (IV <= GlobalUB) { 5432 // <CodeGen rest of pragma>(LB, UB); 5433 // LB += ST; 5434 // UB += ST; 5435 // UB = min(UB, GlobalUB); 5436 // IV = LB; 5437 // } 5438 // 5439 emitCommonSimdLoop( 5440 *this, S, 5441 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5442 if (isOpenMPSimdDirective(S.getDirectiveKind())) 5443 CGF.EmitOMPSimdInit(S); 5444 }, 5445 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop, 5446 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) { 5447 CGF.EmitOMPInnerLoop( 5448 S, LoopScope.requiresCleanups(), Cond, IncExpr, 5449 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 5450 CodeGenLoop(CGF, S, LoopExit); 5451 }, 5452 [&S, StaticChunked](CodeGenFunction &CGF) { 5453 if (StaticChunked) { 5454 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound()); 5455 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound()); 5456 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound()); 5457 CGF.EmitIgnoredExpr(S.getCombinedInit()); 5458 } 5459 }); 5460 }); 5461 EmitBlock(LoopExit.getBlock()); 5462 // Tell the runtime we are done. 5463 RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind()); 5464 } else { 5465 // Emit the outer loop, which requests its work chunk [LB..UB] from 5466 // runtime and runs the inner loop to process it. 5467 const OMPLoopArguments LoopArguments = { 5468 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 5469 IL.getAddress(*this), Chunk}; 5470 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments, 5471 CodeGenLoop); 5472 } 5473 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 5474 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 5475 return CGF.Builder.CreateIsNotNull( 5476 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 5477 }); 5478 } 5479 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 5480 !isOpenMPParallelDirective(S.getDirectiveKind()) && 5481 !isOpenMPTeamsDirective(S.getDirectiveKind())) { 5482 EmitOMPReductionClauseFinal(S, OMPD_simd); 5483 // Emit post-update of the reduction variables if IsLastIter != 0. 5484 emitPostUpdateForReductionClause( 5485 *this, S, [IL, &S](CodeGenFunction &CGF) { 5486 return CGF.Builder.CreateIsNotNull( 5487 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 5488 }); 5489 } 5490 // Emit final copy of the lastprivate variables if IsLastIter != 0. 5491 if (HasLastprivateClause) { 5492 EmitOMPLastprivateClauseFinal( 5493 S, /*NoFinals=*/false, 5494 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 5495 } 5496 } 5497 5498 // We're now done with the loop, so jump to the continuation block. 5499 if (ContBlock) { 5500 EmitBranch(ContBlock); 5501 EmitBlock(ContBlock, true); 5502 } 5503 } 5504 } 5505 5506 void CodeGenFunction::EmitOMPDistributeDirective( 5507 const OMPDistributeDirective &S) { 5508 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5509 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5510 }; 5511 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5512 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 5513 } 5514 5515 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM, 5516 const CapturedStmt *S, 5517 SourceLocation Loc) { 5518 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); 5519 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo; 5520 CGF.CapturedStmtInfo = &CapStmtInfo; 5521 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc); 5522 Fn->setDoesNotRecurse(); 5523 return Fn; 5524 } 5525 5526 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 5527 if (CGM.getLangOpts().OpenMPIRBuilder) { 5528 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 5529 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 5530 5531 if (S.hasClausesOfKind<OMPDependClause>()) { 5532 // The ordered directive with depend clause. 5533 assert(!S.hasAssociatedStmt() && 5534 "No associated statement must be in ordered depend construct."); 5535 InsertPointTy AllocaIP(AllocaInsertPt->getParent(), 5536 AllocaInsertPt->getIterator()); 5537 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) { 5538 unsigned NumLoops = DC->getNumLoops(); 5539 QualType Int64Ty = CGM.getContext().getIntTypeForBitwidth( 5540 /*DestWidth=*/64, /*Signed=*/1); 5541 llvm::SmallVector<llvm::Value *> StoreValues; 5542 for (unsigned I = 0; I < NumLoops; I++) { 5543 const Expr *CounterVal = DC->getLoopData(I); 5544 assert(CounterVal); 5545 llvm::Value *StoreValue = EmitScalarConversion( 5546 EmitScalarExpr(CounterVal), CounterVal->getType(), Int64Ty, 5547 CounterVal->getExprLoc()); 5548 StoreValues.emplace_back(StoreValue); 5549 } 5550 bool IsDependSource = false; 5551 if (DC->getDependencyKind() == OMPC_DEPEND_source) 5552 IsDependSource = true; 5553 Builder.restoreIP(OMPBuilder.createOrderedDepend( 5554 Builder, AllocaIP, NumLoops, StoreValues, ".cnt.addr", 5555 IsDependSource)); 5556 } 5557 } else { 5558 // The ordered directive with threads or simd clause, or without clause. 5559 // Without clause, it behaves as if the threads clause is specified. 5560 const auto *C = S.getSingleClause<OMPSIMDClause>(); 5561 5562 auto FiniCB = [this](InsertPointTy IP) { 5563 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 5564 }; 5565 5566 auto BodyGenCB = [&S, C, this](InsertPointTy AllocaIP, 5567 InsertPointTy CodeGenIP, 5568 llvm::BasicBlock &FiniBB) { 5569 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 5570 if (C) { 5571 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 5572 GenerateOpenMPCapturedVars(*CS, CapturedVars); 5573 llvm::Function *OutlinedFn = 5574 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc()); 5575 assert(S.getBeginLoc().isValid() && 5576 "Outlined function call location must be valid."); 5577 ApplyDebugLocation::CreateDefaultArtificial(*this, S.getBeginLoc()); 5578 OMPBuilderCBHelpers::EmitCaptureStmt(*this, CodeGenIP, FiniBB, 5579 OutlinedFn, CapturedVars); 5580 } else { 5581 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, 5582 FiniBB); 5583 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CS->getCapturedStmt(), 5584 CodeGenIP, FiniBB); 5585 } 5586 }; 5587 5588 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5589 Builder.restoreIP( 5590 OMPBuilder.createOrderedThreadsSimd(Builder, BodyGenCB, FiniCB, !C)); 5591 } 5592 return; 5593 } 5594 5595 if (S.hasClausesOfKind<OMPDependClause>()) { 5596 assert(!S.hasAssociatedStmt() && 5597 "No associated statement must be in ordered depend construct."); 5598 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) 5599 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC); 5600 return; 5601 } 5602 const auto *C = S.getSingleClause<OMPSIMDClause>(); 5603 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF, 5604 PrePostActionTy &Action) { 5605 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 5606 if (C) { 5607 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 5608 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 5609 llvm::Function *OutlinedFn = 5610 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc()); 5611 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(), 5612 OutlinedFn, CapturedVars); 5613 } else { 5614 Action.Enter(CGF); 5615 CGF.EmitStmt(CS->getCapturedStmt()); 5616 } 5617 }; 5618 OMPLexicalScope Scope(*this, S, OMPD_unknown); 5619 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C); 5620 } 5621 5622 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 5623 QualType SrcType, QualType DestType, 5624 SourceLocation Loc) { 5625 assert(CGF.hasScalarEvaluationKind(DestType) && 5626 "DestType must have scalar evaluation kind."); 5627 assert(!Val.isAggregate() && "Must be a scalar or complex."); 5628 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 5629 DestType, Loc) 5630 : CGF.EmitComplexToScalarConversion( 5631 Val.getComplexVal(), SrcType, DestType, Loc); 5632 } 5633 5634 static CodeGenFunction::ComplexPairTy 5635 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 5636 QualType DestType, SourceLocation Loc) { 5637 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 5638 "DestType must have complex evaluation kind."); 5639 CodeGenFunction::ComplexPairTy ComplexVal; 5640 if (Val.isScalar()) { 5641 // Convert the input element to the element type of the complex. 5642 QualType DestElementType = 5643 DestType->castAs<ComplexType>()->getElementType(); 5644 llvm::Value *ScalarVal = CGF.EmitScalarConversion( 5645 Val.getScalarVal(), SrcType, DestElementType, Loc); 5646 ComplexVal = CodeGenFunction::ComplexPairTy( 5647 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 5648 } else { 5649 assert(Val.isComplex() && "Must be a scalar or complex."); 5650 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 5651 QualType DestElementType = 5652 DestType->castAs<ComplexType>()->getElementType(); 5653 ComplexVal.first = CGF.EmitScalarConversion( 5654 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 5655 ComplexVal.second = CGF.EmitScalarConversion( 5656 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 5657 } 5658 return ComplexVal; 5659 } 5660 5661 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 5662 LValue LVal, RValue RVal) { 5663 if (LVal.isGlobalReg()) 5664 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 5665 else 5666 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false); 5667 } 5668 5669 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, 5670 llvm::AtomicOrdering AO, LValue LVal, 5671 SourceLocation Loc) { 5672 if (LVal.isGlobalReg()) 5673 return CGF.EmitLoadOfLValue(LVal, Loc); 5674 return CGF.EmitAtomicLoad( 5675 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO), 5676 LVal.isVolatile()); 5677 } 5678 5679 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal, 5680 QualType RValTy, SourceLocation Loc) { 5681 switch (getEvaluationKind(LVal.getType())) { 5682 case TEK_Scalar: 5683 EmitStoreThroughLValue(RValue::get(convertToScalarValue( 5684 *this, RVal, RValTy, LVal.getType(), Loc)), 5685 LVal); 5686 break; 5687 case TEK_Complex: 5688 EmitStoreOfComplex( 5689 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal, 5690 /*isInit=*/false); 5691 break; 5692 case TEK_Aggregate: 5693 llvm_unreachable("Must be a scalar or complex."); 5694 } 5695 } 5696 5697 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 5698 const Expr *X, const Expr *V, 5699 SourceLocation Loc) { 5700 // v = x; 5701 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 5702 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 5703 LValue XLValue = CGF.EmitLValue(X); 5704 LValue VLValue = CGF.EmitLValue(V); 5705 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc); 5706 // OpenMP, 2.17.7, atomic Construct 5707 // If the read or capture clause is specified and the acquire, acq_rel, or 5708 // seq_cst clause is specified then the strong flush on exit from the atomic 5709 // operation is also an acquire flush. 5710 switch (AO) { 5711 case llvm::AtomicOrdering::Acquire: 5712 case llvm::AtomicOrdering::AcquireRelease: 5713 case llvm::AtomicOrdering::SequentiallyConsistent: 5714 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5715 llvm::AtomicOrdering::Acquire); 5716 break; 5717 case llvm::AtomicOrdering::Monotonic: 5718 case llvm::AtomicOrdering::Release: 5719 break; 5720 case llvm::AtomicOrdering::NotAtomic: 5721 case llvm::AtomicOrdering::Unordered: 5722 llvm_unreachable("Unexpected ordering."); 5723 } 5724 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc); 5725 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 5726 } 5727 5728 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, 5729 llvm::AtomicOrdering AO, const Expr *X, 5730 const Expr *E, SourceLocation Loc) { 5731 // x = expr; 5732 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 5733 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 5734 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5735 // OpenMP, 2.17.7, atomic Construct 5736 // If the write, update, or capture clause is specified and the release, 5737 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5738 // the atomic operation is also a release flush. 5739 switch (AO) { 5740 case llvm::AtomicOrdering::Release: 5741 case llvm::AtomicOrdering::AcquireRelease: 5742 case llvm::AtomicOrdering::SequentiallyConsistent: 5743 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5744 llvm::AtomicOrdering::Release); 5745 break; 5746 case llvm::AtomicOrdering::Acquire: 5747 case llvm::AtomicOrdering::Monotonic: 5748 break; 5749 case llvm::AtomicOrdering::NotAtomic: 5750 case llvm::AtomicOrdering::Unordered: 5751 llvm_unreachable("Unexpected ordering."); 5752 } 5753 } 5754 5755 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 5756 RValue Update, 5757 BinaryOperatorKind BO, 5758 llvm::AtomicOrdering AO, 5759 bool IsXLHSInRHSPart) { 5760 ASTContext &Context = CGF.getContext(); 5761 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 5762 // expression is simple and atomic is allowed for the given type for the 5763 // target platform. 5764 if (BO == BO_Comma || !Update.isScalar() || 5765 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() || 5766 (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 5767 (Update.getScalarVal()->getType() != 5768 X.getAddress(CGF).getElementType())) || 5769 !X.getAddress(CGF).getElementType()->isIntegerTy() || 5770 !Context.getTargetInfo().hasBuiltinAtomic( 5771 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 5772 return std::make_pair(false, RValue::get(nullptr)); 5773 5774 llvm::AtomicRMWInst::BinOp RMWOp; 5775 switch (BO) { 5776 case BO_Add: 5777 RMWOp = llvm::AtomicRMWInst::Add; 5778 break; 5779 case BO_Sub: 5780 if (!IsXLHSInRHSPart) 5781 return std::make_pair(false, RValue::get(nullptr)); 5782 RMWOp = llvm::AtomicRMWInst::Sub; 5783 break; 5784 case BO_And: 5785 RMWOp = llvm::AtomicRMWInst::And; 5786 break; 5787 case BO_Or: 5788 RMWOp = llvm::AtomicRMWInst::Or; 5789 break; 5790 case BO_Xor: 5791 RMWOp = llvm::AtomicRMWInst::Xor; 5792 break; 5793 case BO_LT: 5794 RMWOp = X.getType()->hasSignedIntegerRepresentation() 5795 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 5796 : llvm::AtomicRMWInst::Max) 5797 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 5798 : llvm::AtomicRMWInst::UMax); 5799 break; 5800 case BO_GT: 5801 RMWOp = X.getType()->hasSignedIntegerRepresentation() 5802 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 5803 : llvm::AtomicRMWInst::Min) 5804 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 5805 : llvm::AtomicRMWInst::UMin); 5806 break; 5807 case BO_Assign: 5808 RMWOp = llvm::AtomicRMWInst::Xchg; 5809 break; 5810 case BO_Mul: 5811 case BO_Div: 5812 case BO_Rem: 5813 case BO_Shl: 5814 case BO_Shr: 5815 case BO_LAnd: 5816 case BO_LOr: 5817 return std::make_pair(false, RValue::get(nullptr)); 5818 case BO_PtrMemD: 5819 case BO_PtrMemI: 5820 case BO_LE: 5821 case BO_GE: 5822 case BO_EQ: 5823 case BO_NE: 5824 case BO_Cmp: 5825 case BO_AddAssign: 5826 case BO_SubAssign: 5827 case BO_AndAssign: 5828 case BO_OrAssign: 5829 case BO_XorAssign: 5830 case BO_MulAssign: 5831 case BO_DivAssign: 5832 case BO_RemAssign: 5833 case BO_ShlAssign: 5834 case BO_ShrAssign: 5835 case BO_Comma: 5836 llvm_unreachable("Unsupported atomic update operation"); 5837 } 5838 llvm::Value *UpdateVal = Update.getScalarVal(); 5839 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 5840 UpdateVal = CGF.Builder.CreateIntCast( 5841 IC, X.getAddress(CGF).getElementType(), 5842 X.getType()->hasSignedIntegerRepresentation()); 5843 } 5844 llvm::Value *Res = 5845 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO); 5846 return std::make_pair(true, RValue::get(Res)); 5847 } 5848 5849 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 5850 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 5851 llvm::AtomicOrdering AO, SourceLocation Loc, 5852 const llvm::function_ref<RValue(RValue)> CommonGen) { 5853 // Update expressions are allowed to have the following forms: 5854 // x binop= expr; -> xrval + expr; 5855 // x++, ++x -> xrval + 1; 5856 // x--, --x -> xrval - 1; 5857 // x = x binop expr; -> xrval binop expr 5858 // x = expr Op x; - > expr binop xrval; 5859 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 5860 if (!Res.first) { 5861 if (X.isGlobalReg()) { 5862 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 5863 // 'xrval'. 5864 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 5865 } else { 5866 // Perform compare-and-swap procedure. 5867 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 5868 } 5869 } 5870 return Res; 5871 } 5872 5873 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, 5874 llvm::AtomicOrdering AO, const Expr *X, 5875 const Expr *E, const Expr *UE, 5876 bool IsXLHSInRHSPart, SourceLocation Loc) { 5877 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 5878 "Update expr in 'atomic update' must be a binary operator."); 5879 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 5880 // Update expressions are allowed to have the following forms: 5881 // x binop= expr; -> xrval + expr; 5882 // x++, ++x -> xrval + 1; 5883 // x--, --x -> xrval - 1; 5884 // x = x binop expr; -> xrval binop expr 5885 // x = expr Op x; - > expr binop xrval; 5886 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 5887 LValue XLValue = CGF.EmitLValue(X); 5888 RValue ExprRValue = CGF.EmitAnyExpr(E); 5889 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 5890 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 5891 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 5892 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 5893 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) { 5894 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5895 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 5896 return CGF.EmitAnyExpr(UE); 5897 }; 5898 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 5899 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 5900 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5901 // OpenMP, 2.17.7, atomic Construct 5902 // If the write, update, or capture clause is specified and the release, 5903 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 5904 // the atomic operation is also a release flush. 5905 switch (AO) { 5906 case llvm::AtomicOrdering::Release: 5907 case llvm::AtomicOrdering::AcquireRelease: 5908 case llvm::AtomicOrdering::SequentiallyConsistent: 5909 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 5910 llvm::AtomicOrdering::Release); 5911 break; 5912 case llvm::AtomicOrdering::Acquire: 5913 case llvm::AtomicOrdering::Monotonic: 5914 break; 5915 case llvm::AtomicOrdering::NotAtomic: 5916 case llvm::AtomicOrdering::Unordered: 5917 llvm_unreachable("Unexpected ordering."); 5918 } 5919 } 5920 5921 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 5922 QualType SourceType, QualType ResType, 5923 SourceLocation Loc) { 5924 switch (CGF.getEvaluationKind(ResType)) { 5925 case TEK_Scalar: 5926 return RValue::get( 5927 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 5928 case TEK_Complex: { 5929 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 5930 return RValue::getComplex(Res.first, Res.second); 5931 } 5932 case TEK_Aggregate: 5933 break; 5934 } 5935 llvm_unreachable("Must be a scalar or complex."); 5936 } 5937 5938 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, 5939 llvm::AtomicOrdering AO, 5940 bool IsPostfixUpdate, const Expr *V, 5941 const Expr *X, const Expr *E, 5942 const Expr *UE, bool IsXLHSInRHSPart, 5943 SourceLocation Loc) { 5944 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 5945 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 5946 RValue NewVVal; 5947 LValue VLValue = CGF.EmitLValue(V); 5948 LValue XLValue = CGF.EmitLValue(X); 5949 RValue ExprRValue = CGF.EmitAnyExpr(E); 5950 QualType NewVValType; 5951 if (UE) { 5952 // 'x' is updated with some additional value. 5953 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 5954 "Update expr in 'atomic capture' must be a binary operator."); 5955 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 5956 // Update expressions are allowed to have the following forms: 5957 // x binop= expr; -> xrval + expr; 5958 // x++, ++x -> xrval + 1; 5959 // x--, --x -> xrval - 1; 5960 // x = x binop expr; -> xrval binop expr 5961 // x = expr Op x; - > expr binop xrval; 5962 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 5963 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 5964 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 5965 NewVValType = XRValExpr->getType(); 5966 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 5967 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 5968 IsPostfixUpdate](RValue XRValue) { 5969 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5970 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 5971 RValue Res = CGF.EmitAnyExpr(UE); 5972 NewVVal = IsPostfixUpdate ? XRValue : Res; 5973 return Res; 5974 }; 5975 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 5976 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 5977 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 5978 if (Res.first) { 5979 // 'atomicrmw' instruction was generated. 5980 if (IsPostfixUpdate) { 5981 // Use old value from 'atomicrmw'. 5982 NewVVal = Res.second; 5983 } else { 5984 // 'atomicrmw' does not provide new value, so evaluate it using old 5985 // value of 'x'. 5986 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 5987 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 5988 NewVVal = CGF.EmitAnyExpr(UE); 5989 } 5990 } 5991 } else { 5992 // 'x' is simply rewritten with some 'expr'. 5993 NewVValType = X->getType().getNonReferenceType(); 5994 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 5995 X->getType().getNonReferenceType(), Loc); 5996 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) { 5997 NewVVal = XRValue; 5998 return ExprRValue; 5999 }; 6000 // Try to perform atomicrmw xchg, otherwise simple exchange. 6001 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 6002 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 6003 Loc, Gen); 6004 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 6005 if (Res.first) { 6006 // 'atomicrmw' instruction was generated. 6007 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 6008 } 6009 } 6010 // Emit post-update store to 'v' of old/new 'x' value. 6011 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc); 6012 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 6013 // OpenMP 5.1 removes the required flush for capture clause. 6014 if (CGF.CGM.getLangOpts().OpenMP < 51) { 6015 // OpenMP, 2.17.7, atomic Construct 6016 // If the write, update, or capture clause is specified and the release, 6017 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 6018 // the atomic operation is also a release flush. 6019 // If the read or capture clause is specified and the acquire, acq_rel, or 6020 // seq_cst clause is specified then the strong flush on exit from the atomic 6021 // operation is also an acquire flush. 6022 switch (AO) { 6023 case llvm::AtomicOrdering::Release: 6024 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 6025 llvm::AtomicOrdering::Release); 6026 break; 6027 case llvm::AtomicOrdering::Acquire: 6028 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 6029 llvm::AtomicOrdering::Acquire); 6030 break; 6031 case llvm::AtomicOrdering::AcquireRelease: 6032 case llvm::AtomicOrdering::SequentiallyConsistent: 6033 CGF.CGM.getOpenMPRuntime().emitFlush( 6034 CGF, llvm::None, Loc, llvm::AtomicOrdering::AcquireRelease); 6035 break; 6036 case llvm::AtomicOrdering::Monotonic: 6037 break; 6038 case llvm::AtomicOrdering::NotAtomic: 6039 case llvm::AtomicOrdering::Unordered: 6040 llvm_unreachable("Unexpected ordering."); 6041 } 6042 } 6043 } 6044 6045 static void emitOMPAtomicCompareExpr(CodeGenFunction &CGF, 6046 llvm::AtomicOrdering AO, const Expr *X, 6047 const Expr *E, const Expr *D, 6048 const Expr *CE, bool IsXBinopExpr, 6049 SourceLocation Loc) { 6050 llvm::OpenMPIRBuilder &OMPBuilder = 6051 CGF.CGM.getOpenMPRuntime().getOMPBuilder(); 6052 6053 OMPAtomicCompareOp Op; 6054 assert(isa<BinaryOperator>(CE) && "CE is not a BinaryOperator"); 6055 switch (cast<BinaryOperator>(CE)->getOpcode()) { 6056 case BO_EQ: 6057 Op = OMPAtomicCompareOp::EQ; 6058 break; 6059 case BO_LT: 6060 Op = OMPAtomicCompareOp::MIN; 6061 break; 6062 case BO_GT: 6063 Op = OMPAtomicCompareOp::MAX; 6064 break; 6065 default: 6066 llvm_unreachable("unsupported atomic compare binary operator"); 6067 } 6068 6069 LValue XLVal = CGF.EmitLValue(X); 6070 Address XAddr = XLVal.getAddress(CGF); 6071 llvm::Value *EVal = CGF.EmitScalarExpr(E); 6072 llvm::Value *DVal = D ? CGF.EmitScalarExpr(D) : nullptr; 6073 6074 llvm::OpenMPIRBuilder::AtomicOpValue XOpVal{ 6075 XAddr.getPointer(), XAddr.getElementType(), 6076 X->getType().isVolatileQualified(), 6077 X->getType()->hasSignedIntegerRepresentation()}; 6078 6079 CGF.Builder.restoreIP(OMPBuilder.createAtomicCompare( 6080 CGF.Builder, XOpVal, EVal, DVal, AO, Op, IsXBinopExpr)); 6081 } 6082 6083 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 6084 llvm::AtomicOrdering AO, bool IsPostfixUpdate, 6085 const Expr *X, const Expr *V, const Expr *E, 6086 const Expr *UE, const Expr *D, const Expr *CE, 6087 bool IsXLHSInRHSPart, bool IsCompareCapture, 6088 SourceLocation Loc) { 6089 switch (Kind) { 6090 case OMPC_read: 6091 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc); 6092 break; 6093 case OMPC_write: 6094 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc); 6095 break; 6096 case OMPC_unknown: 6097 case OMPC_update: 6098 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc); 6099 break; 6100 case OMPC_capture: 6101 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE, 6102 IsXLHSInRHSPart, Loc); 6103 break; 6104 case OMPC_compare: { 6105 if (IsCompareCapture) { 6106 // Emit an error here. 6107 unsigned DiagID = CGF.CGM.getDiags().getCustomDiagID( 6108 DiagnosticsEngine::Error, 6109 "'atomic compare capture' is not supported for now"); 6110 CGF.CGM.getDiags().Report(DiagID); 6111 } else { 6112 emitOMPAtomicCompareExpr(CGF, AO, X, E, D, CE, IsXLHSInRHSPart, Loc); 6113 } 6114 break; 6115 } 6116 case OMPC_if: 6117 case OMPC_final: 6118 case OMPC_num_threads: 6119 case OMPC_private: 6120 case OMPC_firstprivate: 6121 case OMPC_lastprivate: 6122 case OMPC_reduction: 6123 case OMPC_task_reduction: 6124 case OMPC_in_reduction: 6125 case OMPC_safelen: 6126 case OMPC_simdlen: 6127 case OMPC_sizes: 6128 case OMPC_full: 6129 case OMPC_partial: 6130 case OMPC_allocator: 6131 case OMPC_allocate: 6132 case OMPC_collapse: 6133 case OMPC_default: 6134 case OMPC_seq_cst: 6135 case OMPC_acq_rel: 6136 case OMPC_acquire: 6137 case OMPC_release: 6138 case OMPC_relaxed: 6139 case OMPC_shared: 6140 case OMPC_linear: 6141 case OMPC_aligned: 6142 case OMPC_copyin: 6143 case OMPC_copyprivate: 6144 case OMPC_flush: 6145 case OMPC_depobj: 6146 case OMPC_proc_bind: 6147 case OMPC_schedule: 6148 case OMPC_ordered: 6149 case OMPC_nowait: 6150 case OMPC_untied: 6151 case OMPC_threadprivate: 6152 case OMPC_depend: 6153 case OMPC_mergeable: 6154 case OMPC_device: 6155 case OMPC_threads: 6156 case OMPC_simd: 6157 case OMPC_map: 6158 case OMPC_num_teams: 6159 case OMPC_thread_limit: 6160 case OMPC_priority: 6161 case OMPC_grainsize: 6162 case OMPC_nogroup: 6163 case OMPC_num_tasks: 6164 case OMPC_hint: 6165 case OMPC_dist_schedule: 6166 case OMPC_defaultmap: 6167 case OMPC_uniform: 6168 case OMPC_to: 6169 case OMPC_from: 6170 case OMPC_use_device_ptr: 6171 case OMPC_use_device_addr: 6172 case OMPC_is_device_ptr: 6173 case OMPC_has_device_addr: 6174 case OMPC_unified_address: 6175 case OMPC_unified_shared_memory: 6176 case OMPC_reverse_offload: 6177 case OMPC_dynamic_allocators: 6178 case OMPC_atomic_default_mem_order: 6179 case OMPC_device_type: 6180 case OMPC_match: 6181 case OMPC_nontemporal: 6182 case OMPC_order: 6183 case OMPC_destroy: 6184 case OMPC_detach: 6185 case OMPC_inclusive: 6186 case OMPC_exclusive: 6187 case OMPC_uses_allocators: 6188 case OMPC_affinity: 6189 case OMPC_init: 6190 case OMPC_inbranch: 6191 case OMPC_notinbranch: 6192 case OMPC_link: 6193 case OMPC_indirect: 6194 case OMPC_use: 6195 case OMPC_novariants: 6196 case OMPC_nocontext: 6197 case OMPC_filter: 6198 case OMPC_when: 6199 case OMPC_adjust_args: 6200 case OMPC_append_args: 6201 case OMPC_memory_order: 6202 case OMPC_bind: 6203 case OMPC_align: 6204 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 6205 } 6206 } 6207 6208 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 6209 llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic; 6210 bool MemOrderingSpecified = false; 6211 if (S.getSingleClause<OMPSeqCstClause>()) { 6212 AO = llvm::AtomicOrdering::SequentiallyConsistent; 6213 MemOrderingSpecified = true; 6214 } else if (S.getSingleClause<OMPAcqRelClause>()) { 6215 AO = llvm::AtomicOrdering::AcquireRelease; 6216 MemOrderingSpecified = true; 6217 } else if (S.getSingleClause<OMPAcquireClause>()) { 6218 AO = llvm::AtomicOrdering::Acquire; 6219 MemOrderingSpecified = true; 6220 } else if (S.getSingleClause<OMPReleaseClause>()) { 6221 AO = llvm::AtomicOrdering::Release; 6222 MemOrderingSpecified = true; 6223 } else if (S.getSingleClause<OMPRelaxedClause>()) { 6224 AO = llvm::AtomicOrdering::Monotonic; 6225 MemOrderingSpecified = true; 6226 } 6227 llvm::SmallSet<OpenMPClauseKind, 2> KindsEncountered; 6228 OpenMPClauseKind Kind = OMPC_unknown; 6229 for (const OMPClause *C : S.clauses()) { 6230 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause, 6231 // if it is first). 6232 OpenMPClauseKind K = C->getClauseKind(); 6233 if (K == OMPC_seq_cst || K == OMPC_acq_rel || K == OMPC_acquire || 6234 K == OMPC_release || K == OMPC_relaxed || K == OMPC_hint) 6235 continue; 6236 Kind = K; 6237 KindsEncountered.insert(K); 6238 } 6239 bool IsCompareCapture = false; 6240 if (KindsEncountered.contains(OMPC_compare) && 6241 KindsEncountered.contains(OMPC_capture)) { 6242 IsCompareCapture = true; 6243 Kind = OMPC_compare; 6244 } 6245 if (!MemOrderingSpecified) { 6246 llvm::AtomicOrdering DefaultOrder = 6247 CGM.getOpenMPRuntime().getDefaultMemoryOrdering(); 6248 if (DefaultOrder == llvm::AtomicOrdering::Monotonic || 6249 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent || 6250 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease && 6251 Kind == OMPC_capture)) { 6252 AO = DefaultOrder; 6253 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) { 6254 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) { 6255 AO = llvm::AtomicOrdering::Release; 6256 } else if (Kind == OMPC_read) { 6257 assert(Kind == OMPC_read && "Unexpected atomic kind."); 6258 AO = llvm::AtomicOrdering::Acquire; 6259 } 6260 } 6261 } 6262 6263 LexicalScope Scope(*this, S.getSourceRange()); 6264 EmitStopPoint(S.getAssociatedStmt()); 6265 emitOMPAtomicExpr(*this, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(), 6266 S.getExpr(), S.getUpdateExpr(), S.getD(), S.getCondExpr(), 6267 S.isXLHSInRHSPart(), IsCompareCapture, S.getBeginLoc()); 6268 } 6269 6270 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 6271 const OMPExecutableDirective &S, 6272 const RegionCodeGenTy &CodeGen) { 6273 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind())); 6274 CodeGenModule &CGM = CGF.CGM; 6275 6276 // On device emit this construct as inlined code. 6277 if (CGM.getLangOpts().OpenMPIsDevice) { 6278 OMPLexicalScope Scope(CGF, S, OMPD_target); 6279 CGM.getOpenMPRuntime().emitInlinedDirective( 6280 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6281 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 6282 }); 6283 return; 6284 } 6285 6286 auto LPCRegion = CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S); 6287 llvm::Function *Fn = nullptr; 6288 llvm::Constant *FnID = nullptr; 6289 6290 const Expr *IfCond = nullptr; 6291 // Check for the at most one if clause associated with the target region. 6292 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 6293 if (C->getNameModifier() == OMPD_unknown || 6294 C->getNameModifier() == OMPD_target) { 6295 IfCond = C->getCondition(); 6296 break; 6297 } 6298 } 6299 6300 // Check if we have any device clause associated with the directive. 6301 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device( 6302 nullptr, OMPC_DEVICE_unknown); 6303 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 6304 Device.setPointerAndInt(C->getDevice(), C->getModifier()); 6305 6306 // Check if we have an if clause whose conditional always evaluates to false 6307 // or if we do not have any targets specified. If so the target region is not 6308 // an offload entry point. 6309 bool IsOffloadEntry = true; 6310 if (IfCond) { 6311 bool Val; 6312 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val) 6313 IsOffloadEntry = false; 6314 } 6315 if (CGM.getLangOpts().OMPTargetTriples.empty()) 6316 IsOffloadEntry = false; 6317 6318 if (CGM.getLangOpts().OpenMPOffloadMandatory && !IsOffloadEntry) { 6319 unsigned DiagID = CGM.getDiags().getCustomDiagID( 6320 DiagnosticsEngine::Error, 6321 "No offloading entry generated while offloading is mandatory."); 6322 CGM.getDiags().Report(DiagID); 6323 } 6324 6325 assert(CGF.CurFuncDecl && "No parent declaration for target region!"); 6326 StringRef ParentName; 6327 // In case we have Ctors/Dtors we use the complete type variant to produce 6328 // the mangling of the device outlined kernel. 6329 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl)) 6330 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete)); 6331 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl)) 6332 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete)); 6333 else 6334 ParentName = 6335 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl))); 6336 6337 // Emit target region as a standalone region. 6338 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID, 6339 IsOffloadEntry, CodeGen); 6340 OMPLexicalScope Scope(CGF, S, OMPD_task); 6341 auto &&SizeEmitter = 6342 [IsOffloadEntry](CodeGenFunction &CGF, 6343 const OMPLoopDirective &D) -> llvm::Value * { 6344 if (IsOffloadEntry) { 6345 OMPLoopScope(CGF, D); 6346 // Emit calculation of the iterations count. 6347 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations()); 6348 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty, 6349 /*isSigned=*/false); 6350 return NumIterations; 6351 } 6352 return nullptr; 6353 }; 6354 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device, 6355 SizeEmitter); 6356 } 6357 6358 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, 6359 PrePostActionTy &Action) { 6360 Action.Enter(CGF); 6361 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6362 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6363 CGF.EmitOMPPrivateClause(S, PrivateScope); 6364 (void)PrivateScope.Privatize(); 6365 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 6366 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 6367 6368 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt()); 6369 CGF.EnsureInsertPoint(); 6370 } 6371 6372 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 6373 StringRef ParentName, 6374 const OMPTargetDirective &S) { 6375 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6376 emitTargetRegion(CGF, S, Action); 6377 }; 6378 llvm::Function *Fn; 6379 llvm::Constant *Addr; 6380 // Emit target region as a standalone region. 6381 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6382 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6383 assert(Fn && Addr && "Target device function emission failed."); 6384 } 6385 6386 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) { 6387 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6388 emitTargetRegion(CGF, S, Action); 6389 }; 6390 emitCommonOMPTargetDirective(*this, S, CodeGen); 6391 } 6392 6393 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, 6394 const OMPExecutableDirective &S, 6395 OpenMPDirectiveKind InnermostKind, 6396 const RegionCodeGenTy &CodeGen) { 6397 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams); 6398 llvm::Function *OutlinedFn = 6399 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction( 6400 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 6401 6402 const auto *NT = S.getSingleClause<OMPNumTeamsClause>(); 6403 const auto *TL = S.getSingleClause<OMPThreadLimitClause>(); 6404 if (NT || TL) { 6405 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr; 6406 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr; 6407 6408 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit, 6409 S.getBeginLoc()); 6410 } 6411 6412 OMPTeamsScope Scope(CGF, S); 6413 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 6414 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 6415 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn, 6416 CapturedVars); 6417 } 6418 6419 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) { 6420 // Emit teams region as a standalone region. 6421 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6422 Action.Enter(CGF); 6423 OMPPrivateScope PrivateScope(CGF); 6424 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6425 CGF.EmitOMPPrivateClause(S, PrivateScope); 6426 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6427 (void)PrivateScope.Privatize(); 6428 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt()); 6429 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6430 }; 6431 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 6432 emitPostUpdateForReductionClause(*this, S, 6433 [](CodeGenFunction &) { return nullptr; }); 6434 } 6435 6436 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 6437 const OMPTargetTeamsDirective &S) { 6438 auto *CS = S.getCapturedStmt(OMPD_teams); 6439 Action.Enter(CGF); 6440 // Emit teams region as a standalone region. 6441 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 6442 Action.Enter(CGF); 6443 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6444 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 6445 CGF.EmitOMPPrivateClause(S, PrivateScope); 6446 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6447 (void)PrivateScope.Privatize(); 6448 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 6449 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 6450 CGF.EmitStmt(CS->getCapturedStmt()); 6451 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6452 }; 6453 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen); 6454 emitPostUpdateForReductionClause(CGF, S, 6455 [](CodeGenFunction &) { return nullptr; }); 6456 } 6457 6458 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 6459 CodeGenModule &CGM, StringRef ParentName, 6460 const OMPTargetTeamsDirective &S) { 6461 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6462 emitTargetTeamsRegion(CGF, Action, S); 6463 }; 6464 llvm::Function *Fn; 6465 llvm::Constant *Addr; 6466 // Emit target region as a standalone region. 6467 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6468 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6469 assert(Fn && Addr && "Target device function emission failed."); 6470 } 6471 6472 void CodeGenFunction::EmitOMPTargetTeamsDirective( 6473 const OMPTargetTeamsDirective &S) { 6474 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6475 emitTargetTeamsRegion(CGF, Action, S); 6476 }; 6477 emitCommonOMPTargetDirective(*this, S, CodeGen); 6478 } 6479 6480 static void 6481 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 6482 const OMPTargetTeamsDistributeDirective &S) { 6483 Action.Enter(CGF); 6484 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6485 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6486 }; 6487 6488 // Emit teams region as a standalone region. 6489 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6490 PrePostActionTy &Action) { 6491 Action.Enter(CGF); 6492 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6493 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6494 (void)PrivateScope.Privatize(); 6495 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6496 CodeGenDistribute); 6497 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6498 }; 6499 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen); 6500 emitPostUpdateForReductionClause(CGF, S, 6501 [](CodeGenFunction &) { return nullptr; }); 6502 } 6503 6504 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 6505 CodeGenModule &CGM, StringRef ParentName, 6506 const OMPTargetTeamsDistributeDirective &S) { 6507 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6508 emitTargetTeamsDistributeRegion(CGF, Action, S); 6509 }; 6510 llvm::Function *Fn; 6511 llvm::Constant *Addr; 6512 // Emit target region as a standalone region. 6513 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6514 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6515 assert(Fn && Addr && "Target device function emission failed."); 6516 } 6517 6518 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective( 6519 const OMPTargetTeamsDistributeDirective &S) { 6520 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6521 emitTargetTeamsDistributeRegion(CGF, Action, S); 6522 }; 6523 emitCommonOMPTargetDirective(*this, S, CodeGen); 6524 } 6525 6526 static void emitTargetTeamsDistributeSimdRegion( 6527 CodeGenFunction &CGF, PrePostActionTy &Action, 6528 const OMPTargetTeamsDistributeSimdDirective &S) { 6529 Action.Enter(CGF); 6530 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6531 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6532 }; 6533 6534 // Emit teams region as a standalone region. 6535 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6536 PrePostActionTy &Action) { 6537 Action.Enter(CGF); 6538 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6539 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6540 (void)PrivateScope.Privatize(); 6541 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6542 CodeGenDistribute); 6543 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6544 }; 6545 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen); 6546 emitPostUpdateForReductionClause(CGF, S, 6547 [](CodeGenFunction &) { return nullptr; }); 6548 } 6549 6550 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 6551 CodeGenModule &CGM, StringRef ParentName, 6552 const OMPTargetTeamsDistributeSimdDirective &S) { 6553 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6554 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 6555 }; 6556 llvm::Function *Fn; 6557 llvm::Constant *Addr; 6558 // Emit target region as a standalone region. 6559 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6560 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6561 assert(Fn && Addr && "Target device function emission failed."); 6562 } 6563 6564 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective( 6565 const OMPTargetTeamsDistributeSimdDirective &S) { 6566 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6567 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 6568 }; 6569 emitCommonOMPTargetDirective(*this, S, CodeGen); 6570 } 6571 6572 void CodeGenFunction::EmitOMPTeamsDistributeDirective( 6573 const OMPTeamsDistributeDirective &S) { 6574 6575 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6576 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6577 }; 6578 6579 // Emit teams region as a standalone region. 6580 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6581 PrePostActionTy &Action) { 6582 Action.Enter(CGF); 6583 OMPPrivateScope PrivateScope(CGF); 6584 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6585 (void)PrivateScope.Privatize(); 6586 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6587 CodeGenDistribute); 6588 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6589 }; 6590 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 6591 emitPostUpdateForReductionClause(*this, S, 6592 [](CodeGenFunction &) { return nullptr; }); 6593 } 6594 6595 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective( 6596 const OMPTeamsDistributeSimdDirective &S) { 6597 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6598 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 6599 }; 6600 6601 // Emit teams region as a standalone region. 6602 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6603 PrePostActionTy &Action) { 6604 Action.Enter(CGF); 6605 OMPPrivateScope PrivateScope(CGF); 6606 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6607 (void)PrivateScope.Privatize(); 6608 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd, 6609 CodeGenDistribute); 6610 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6611 }; 6612 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen); 6613 emitPostUpdateForReductionClause(*this, S, 6614 [](CodeGenFunction &) { return nullptr; }); 6615 } 6616 6617 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective( 6618 const OMPTeamsDistributeParallelForDirective &S) { 6619 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6620 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6621 S.getDistInc()); 6622 }; 6623 6624 // Emit teams region as a standalone region. 6625 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6626 PrePostActionTy &Action) { 6627 Action.Enter(CGF); 6628 OMPPrivateScope PrivateScope(CGF); 6629 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6630 (void)PrivateScope.Privatize(); 6631 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 6632 CodeGenDistribute); 6633 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6634 }; 6635 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen); 6636 emitPostUpdateForReductionClause(*this, S, 6637 [](CodeGenFunction &) { return nullptr; }); 6638 } 6639 6640 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective( 6641 const OMPTeamsDistributeParallelForSimdDirective &S) { 6642 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6643 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6644 S.getDistInc()); 6645 }; 6646 6647 // Emit teams region as a standalone region. 6648 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6649 PrePostActionTy &Action) { 6650 Action.Enter(CGF); 6651 OMPPrivateScope PrivateScope(CGF); 6652 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6653 (void)PrivateScope.Privatize(); 6654 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6655 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6656 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6657 }; 6658 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd, 6659 CodeGen); 6660 emitPostUpdateForReductionClause(*this, S, 6661 [](CodeGenFunction &) { return nullptr; }); 6662 } 6663 6664 void CodeGenFunction::EmitOMPInteropDirective(const OMPInteropDirective &S) { 6665 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 6666 llvm::Value *Device = nullptr; 6667 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 6668 Device = EmitScalarExpr(C->getDevice()); 6669 6670 llvm::Value *NumDependences = nullptr; 6671 llvm::Value *DependenceAddress = nullptr; 6672 if (const auto *DC = S.getSingleClause<OMPDependClause>()) { 6673 OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(), 6674 DC->getModifier()); 6675 Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end()); 6676 std::pair<llvm::Value *, Address> DependencePair = 6677 CGM.getOpenMPRuntime().emitDependClause(*this, Dependencies, 6678 DC->getBeginLoc()); 6679 NumDependences = DependencePair.first; 6680 DependenceAddress = Builder.CreatePointerCast( 6681 DependencePair.second.getPointer(), CGM.Int8PtrTy); 6682 } 6683 6684 assert(!(S.hasClausesOfKind<OMPNowaitClause>() && 6685 !(S.getSingleClause<OMPInitClause>() || 6686 S.getSingleClause<OMPDestroyClause>() || 6687 S.getSingleClause<OMPUseClause>())) && 6688 "OMPNowaitClause clause is used separately in OMPInteropDirective."); 6689 6690 if (const auto *C = S.getSingleClause<OMPInitClause>()) { 6691 llvm::Value *InteropvarPtr = 6692 EmitLValue(C->getInteropVar()).getPointer(*this); 6693 llvm::omp::OMPInteropType InteropType = llvm::omp::OMPInteropType::Unknown; 6694 if (C->getIsTarget()) { 6695 InteropType = llvm::omp::OMPInteropType::Target; 6696 } else { 6697 assert(C->getIsTargetSync() && "Expected interop-type target/targetsync"); 6698 InteropType = llvm::omp::OMPInteropType::TargetSync; 6699 } 6700 OMPBuilder.createOMPInteropInit(Builder, InteropvarPtr, InteropType, Device, 6701 NumDependences, DependenceAddress, 6702 S.hasClausesOfKind<OMPNowaitClause>()); 6703 } else if (const auto *C = S.getSingleClause<OMPDestroyClause>()) { 6704 llvm::Value *InteropvarPtr = 6705 EmitLValue(C->getInteropVar()).getPointer(*this); 6706 OMPBuilder.createOMPInteropDestroy(Builder, InteropvarPtr, Device, 6707 NumDependences, DependenceAddress, 6708 S.hasClausesOfKind<OMPNowaitClause>()); 6709 } else if (const auto *C = S.getSingleClause<OMPUseClause>()) { 6710 llvm::Value *InteropvarPtr = 6711 EmitLValue(C->getInteropVar()).getPointer(*this); 6712 OMPBuilder.createOMPInteropUse(Builder, InteropvarPtr, Device, 6713 NumDependences, DependenceAddress, 6714 S.hasClausesOfKind<OMPNowaitClause>()); 6715 } 6716 } 6717 6718 static void emitTargetTeamsDistributeParallelForRegion( 6719 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, 6720 PrePostActionTy &Action) { 6721 Action.Enter(CGF); 6722 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6723 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6724 S.getDistInc()); 6725 }; 6726 6727 // Emit teams region as a standalone region. 6728 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6729 PrePostActionTy &Action) { 6730 Action.Enter(CGF); 6731 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6732 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6733 (void)PrivateScope.Privatize(); 6734 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6735 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6736 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6737 }; 6738 6739 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for, 6740 CodeGenTeams); 6741 emitPostUpdateForReductionClause(CGF, S, 6742 [](CodeGenFunction &) { return nullptr; }); 6743 } 6744 6745 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 6746 CodeGenModule &CGM, StringRef ParentName, 6747 const OMPTargetTeamsDistributeParallelForDirective &S) { 6748 // Emit SPMD target teams distribute parallel for region as a standalone 6749 // region. 6750 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6751 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 6752 }; 6753 llvm::Function *Fn; 6754 llvm::Constant *Addr; 6755 // Emit target region as a standalone region. 6756 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6757 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6758 assert(Fn && Addr && "Target device function emission failed."); 6759 } 6760 6761 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective( 6762 const OMPTargetTeamsDistributeParallelForDirective &S) { 6763 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6764 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 6765 }; 6766 emitCommonOMPTargetDirective(*this, S, CodeGen); 6767 } 6768 6769 static void emitTargetTeamsDistributeParallelForSimdRegion( 6770 CodeGenFunction &CGF, 6771 const OMPTargetTeamsDistributeParallelForSimdDirective &S, 6772 PrePostActionTy &Action) { 6773 Action.Enter(CGF); 6774 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 6775 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 6776 S.getDistInc()); 6777 }; 6778 6779 // Emit teams region as a standalone region. 6780 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 6781 PrePostActionTy &Action) { 6782 Action.Enter(CGF); 6783 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 6784 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 6785 (void)PrivateScope.Privatize(); 6786 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 6787 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 6788 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 6789 }; 6790 6791 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd, 6792 CodeGenTeams); 6793 emitPostUpdateForReductionClause(CGF, S, 6794 [](CodeGenFunction &) { return nullptr; }); 6795 } 6796 6797 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 6798 CodeGenModule &CGM, StringRef ParentName, 6799 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 6800 // Emit SPMD target teams distribute parallel for simd region as a standalone 6801 // region. 6802 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6803 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 6804 }; 6805 llvm::Function *Fn; 6806 llvm::Constant *Addr; 6807 // Emit target region as a standalone region. 6808 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 6809 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 6810 assert(Fn && Addr && "Target device function emission failed."); 6811 } 6812 6813 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective( 6814 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 6815 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 6816 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 6817 }; 6818 emitCommonOMPTargetDirective(*this, S, CodeGen); 6819 } 6820 6821 void CodeGenFunction::EmitOMPCancellationPointDirective( 6822 const OMPCancellationPointDirective &S) { 6823 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(), 6824 S.getCancelRegion()); 6825 } 6826 6827 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 6828 const Expr *IfCond = nullptr; 6829 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 6830 if (C->getNameModifier() == OMPD_unknown || 6831 C->getNameModifier() == OMPD_cancel) { 6832 IfCond = C->getCondition(); 6833 break; 6834 } 6835 } 6836 if (CGM.getLangOpts().OpenMPIRBuilder) { 6837 llvm::OpenMPIRBuilder &OMPBuilder = CGM.getOpenMPRuntime().getOMPBuilder(); 6838 // TODO: This check is necessary as we only generate `omp parallel` through 6839 // the OpenMPIRBuilder for now. 6840 if (S.getCancelRegion() == OMPD_parallel || 6841 S.getCancelRegion() == OMPD_sections || 6842 S.getCancelRegion() == OMPD_section) { 6843 llvm::Value *IfCondition = nullptr; 6844 if (IfCond) 6845 IfCondition = EmitScalarExpr(IfCond, 6846 /*IgnoreResultAssign=*/true); 6847 return Builder.restoreIP( 6848 OMPBuilder.createCancel(Builder, IfCondition, S.getCancelRegion())); 6849 } 6850 } 6851 6852 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond, 6853 S.getCancelRegion()); 6854 } 6855 6856 CodeGenFunction::JumpDest 6857 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 6858 if (Kind == OMPD_parallel || Kind == OMPD_task || 6859 Kind == OMPD_target_parallel || Kind == OMPD_taskloop || 6860 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop) 6861 return ReturnBlock; 6862 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections || 6863 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for || 6864 Kind == OMPD_distribute_parallel_for || 6865 Kind == OMPD_target_parallel_for || 6866 Kind == OMPD_teams_distribute_parallel_for || 6867 Kind == OMPD_target_teams_distribute_parallel_for); 6868 return OMPCancelStack.getExitBlock(); 6869 } 6870 6871 void CodeGenFunction::EmitOMPUseDevicePtrClause( 6872 const OMPUseDevicePtrClause &C, OMPPrivateScope &PrivateScope, 6873 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 6874 auto OrigVarIt = C.varlist_begin(); 6875 auto InitIt = C.inits().begin(); 6876 for (const Expr *PvtVarIt : C.private_copies()) { 6877 const auto *OrigVD = 6878 cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl()); 6879 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl()); 6880 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl()); 6881 6882 // In order to identify the right initializer we need to match the 6883 // declaration used by the mapping logic. In some cases we may get 6884 // OMPCapturedExprDecl that refers to the original declaration. 6885 const ValueDecl *MatchingVD = OrigVD; 6886 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 6887 // OMPCapturedExprDecl are used to privative fields of the current 6888 // structure. 6889 const auto *ME = cast<MemberExpr>(OED->getInit()); 6890 assert(isa<CXXThisExpr>(ME->getBase()) && 6891 "Base should be the current struct!"); 6892 MatchingVD = ME->getMemberDecl(); 6893 } 6894 6895 // If we don't have information about the current list item, move on to 6896 // the next one. 6897 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 6898 if (InitAddrIt == CaptureDeviceAddrMap.end()) 6899 continue; 6900 6901 // Initialize the temporary initialization variable with the address 6902 // we get from the runtime library. We have to cast the source address 6903 // because it is always a void *. References are materialized in the 6904 // privatization scope, so the initialization here disregards the fact 6905 // the original variable is a reference. 6906 llvm::Type *Ty = ConvertTypeForMem(OrigVD->getType().getNonReferenceType()); 6907 Address InitAddr = Builder.CreateElementBitCast(InitAddrIt->second, Ty); 6908 setAddrOfLocalVar(InitVD, InitAddr); 6909 6910 // Emit private declaration, it will be initialized by the value we 6911 // declaration we just added to the local declarations map. 6912 EmitDecl(*PvtVD); 6913 6914 // The initialization variables reached its purpose in the emission 6915 // of the previous declaration, so we don't need it anymore. 6916 LocalDeclMap.erase(InitVD); 6917 6918 // Return the address of the private variable. 6919 bool IsRegistered = 6920 PrivateScope.addPrivate(OrigVD, GetAddrOfLocalVar(PvtVD)); 6921 assert(IsRegistered && "firstprivate var already registered as private"); 6922 // Silence the warning about unused variable. 6923 (void)IsRegistered; 6924 6925 ++OrigVarIt; 6926 ++InitIt; 6927 } 6928 } 6929 6930 static const VarDecl *getBaseDecl(const Expr *Ref) { 6931 const Expr *Base = Ref->IgnoreParenImpCasts(); 6932 while (const auto *OASE = dyn_cast<OMPArraySectionExpr>(Base)) 6933 Base = OASE->getBase()->IgnoreParenImpCasts(); 6934 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Base)) 6935 Base = ASE->getBase()->IgnoreParenImpCasts(); 6936 return cast<VarDecl>(cast<DeclRefExpr>(Base)->getDecl()); 6937 } 6938 6939 void CodeGenFunction::EmitOMPUseDeviceAddrClause( 6940 const OMPUseDeviceAddrClause &C, OMPPrivateScope &PrivateScope, 6941 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 6942 llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>, 4> Processed; 6943 for (const Expr *Ref : C.varlists()) { 6944 const VarDecl *OrigVD = getBaseDecl(Ref); 6945 if (!Processed.insert(OrigVD).second) 6946 continue; 6947 // In order to identify the right initializer we need to match the 6948 // declaration used by the mapping logic. In some cases we may get 6949 // OMPCapturedExprDecl that refers to the original declaration. 6950 const ValueDecl *MatchingVD = OrigVD; 6951 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 6952 // OMPCapturedExprDecl are used to privative fields of the current 6953 // structure. 6954 const auto *ME = cast<MemberExpr>(OED->getInit()); 6955 assert(isa<CXXThisExpr>(ME->getBase()) && 6956 "Base should be the current struct!"); 6957 MatchingVD = ME->getMemberDecl(); 6958 } 6959 6960 // If we don't have information about the current list item, move on to 6961 // the next one. 6962 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 6963 if (InitAddrIt == CaptureDeviceAddrMap.end()) 6964 continue; 6965 6966 Address PrivAddr = InitAddrIt->getSecond(); 6967 // For declrefs and variable length array need to load the pointer for 6968 // correct mapping, since the pointer to the data was passed to the runtime. 6969 if (isa<DeclRefExpr>(Ref->IgnoreParenImpCasts()) || 6970 MatchingVD->getType()->isArrayType()) { 6971 QualType PtrTy = getContext().getPointerType( 6972 OrigVD->getType().getNonReferenceType()); 6973 PrivAddr = EmitLoadOfPointer( 6974 Builder.CreateElementBitCast(PrivAddr, ConvertTypeForMem(PtrTy)), 6975 PtrTy->castAs<PointerType>()); 6976 } 6977 6978 (void)PrivateScope.addPrivate(OrigVD, PrivAddr); 6979 } 6980 } 6981 6982 // Generate the instructions for '#pragma omp target data' directive. 6983 void CodeGenFunction::EmitOMPTargetDataDirective( 6984 const OMPTargetDataDirective &S) { 6985 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true, 6986 /*SeparateBeginEndCalls=*/true); 6987 6988 // Create a pre/post action to signal the privatization of the device pointer. 6989 // This action can be replaced by the OpenMP runtime code generation to 6990 // deactivate privatization. 6991 bool PrivatizeDevicePointers = false; 6992 class DevicePointerPrivActionTy : public PrePostActionTy { 6993 bool &PrivatizeDevicePointers; 6994 6995 public: 6996 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers) 6997 : PrivatizeDevicePointers(PrivatizeDevicePointers) {} 6998 void Enter(CodeGenFunction &CGF) override { 6999 PrivatizeDevicePointers = true; 7000 } 7001 }; 7002 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers); 7003 7004 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers]( 7005 CodeGenFunction &CGF, PrePostActionTy &Action) { 7006 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 7007 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 7008 }; 7009 7010 // Codegen that selects whether to generate the privatization code or not. 7011 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers, 7012 &InnermostCodeGen](CodeGenFunction &CGF, 7013 PrePostActionTy &Action) { 7014 RegionCodeGenTy RCG(InnermostCodeGen); 7015 PrivatizeDevicePointers = false; 7016 7017 // Call the pre-action to change the status of PrivatizeDevicePointers if 7018 // needed. 7019 Action.Enter(CGF); 7020 7021 if (PrivatizeDevicePointers) { 7022 OMPPrivateScope PrivateScope(CGF); 7023 // Emit all instances of the use_device_ptr clause. 7024 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>()) 7025 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope, 7026 Info.CaptureDeviceAddrMap); 7027 for (const auto *C : S.getClausesOfKind<OMPUseDeviceAddrClause>()) 7028 CGF.EmitOMPUseDeviceAddrClause(*C, PrivateScope, 7029 Info.CaptureDeviceAddrMap); 7030 (void)PrivateScope.Privatize(); 7031 RCG(CGF); 7032 } else { 7033 OMPLexicalScope Scope(CGF, S, OMPD_unknown); 7034 RCG(CGF); 7035 } 7036 }; 7037 7038 // Forward the provided action to the privatization codegen. 7039 RegionCodeGenTy PrivRCG(PrivCodeGen); 7040 PrivRCG.setAction(Action); 7041 7042 // Notwithstanding the body of the region is emitted as inlined directive, 7043 // we don't use an inline scope as changes in the references inside the 7044 // region are expected to be visible outside, so we do not privative them. 7045 OMPLexicalScope Scope(CGF, S); 7046 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, 7047 PrivRCG); 7048 }; 7049 7050 RegionCodeGenTy RCG(CodeGen); 7051 7052 // If we don't have target devices, don't bother emitting the data mapping 7053 // code. 7054 if (CGM.getLangOpts().OMPTargetTriples.empty()) { 7055 RCG(*this); 7056 return; 7057 } 7058 7059 // Check if we have any if clause associated with the directive. 7060 const Expr *IfCond = nullptr; 7061 if (const auto *C = S.getSingleClause<OMPIfClause>()) 7062 IfCond = C->getCondition(); 7063 7064 // Check if we have any device clause associated with the directive. 7065 const Expr *Device = nullptr; 7066 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 7067 Device = C->getDevice(); 7068 7069 // Set the action to signal privatization of device pointers. 7070 RCG.setAction(PrivAction); 7071 7072 // Emit region code. 7073 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG, 7074 Info); 7075 } 7076 7077 void CodeGenFunction::EmitOMPTargetEnterDataDirective( 7078 const OMPTargetEnterDataDirective &S) { 7079 // If we don't have target devices, don't bother emitting the data mapping 7080 // code. 7081 if (CGM.getLangOpts().OMPTargetTriples.empty()) 7082 return; 7083 7084 // Check if we have any if clause associated with the directive. 7085 const Expr *IfCond = nullptr; 7086 if (const auto *C = S.getSingleClause<OMPIfClause>()) 7087 IfCond = C->getCondition(); 7088 7089 // Check if we have any device clause associated with the directive. 7090 const Expr *Device = nullptr; 7091 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 7092 Device = C->getDevice(); 7093 7094 OMPLexicalScope Scope(*this, S, OMPD_task); 7095 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 7096 } 7097 7098 void CodeGenFunction::EmitOMPTargetExitDataDirective( 7099 const OMPTargetExitDataDirective &S) { 7100 // If we don't have target devices, don't bother emitting the data mapping 7101 // code. 7102 if (CGM.getLangOpts().OMPTargetTriples.empty()) 7103 return; 7104 7105 // Check if we have any if clause associated with the directive. 7106 const Expr *IfCond = nullptr; 7107 if (const auto *C = S.getSingleClause<OMPIfClause>()) 7108 IfCond = C->getCondition(); 7109 7110 // Check if we have any device clause associated with the directive. 7111 const Expr *Device = nullptr; 7112 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 7113 Device = C->getDevice(); 7114 7115 OMPLexicalScope Scope(*this, S, OMPD_task); 7116 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 7117 } 7118 7119 static void emitTargetParallelRegion(CodeGenFunction &CGF, 7120 const OMPTargetParallelDirective &S, 7121 PrePostActionTy &Action) { 7122 // Get the captured statement associated with the 'parallel' region. 7123 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 7124 Action.Enter(CGF); 7125 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 7126 Action.Enter(CGF); 7127 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 7128 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 7129 CGF.EmitOMPPrivateClause(S, PrivateScope); 7130 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 7131 (void)PrivateScope.Privatize(); 7132 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 7133 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 7134 // TODO: Add support for clauses. 7135 CGF.EmitStmt(CS->getCapturedStmt()); 7136 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 7137 }; 7138 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen, 7139 emitEmptyBoundParameters); 7140 emitPostUpdateForReductionClause(CGF, S, 7141 [](CodeGenFunction &) { return nullptr; }); 7142 } 7143 7144 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 7145 CodeGenModule &CGM, StringRef ParentName, 7146 const OMPTargetParallelDirective &S) { 7147 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7148 emitTargetParallelRegion(CGF, S, Action); 7149 }; 7150 llvm::Function *Fn; 7151 llvm::Constant *Addr; 7152 // Emit target region as a standalone region. 7153 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 7154 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 7155 assert(Fn && Addr && "Target device function emission failed."); 7156 } 7157 7158 void CodeGenFunction::EmitOMPTargetParallelDirective( 7159 const OMPTargetParallelDirective &S) { 7160 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7161 emitTargetParallelRegion(CGF, S, Action); 7162 }; 7163 emitCommonOMPTargetDirective(*this, S, CodeGen); 7164 } 7165 7166 static void emitTargetParallelForRegion(CodeGenFunction &CGF, 7167 const OMPTargetParallelForDirective &S, 7168 PrePostActionTy &Action) { 7169 Action.Enter(CGF); 7170 // Emit directive as a combined directive that consists of two implicit 7171 // directives: 'parallel' with 'for' directive. 7172 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7173 Action.Enter(CGF); 7174 CodeGenFunction::OMPCancelStackRAII CancelRegion( 7175 CGF, OMPD_target_parallel_for, S.hasCancel()); 7176 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 7177 emitDispatchForLoopBounds); 7178 }; 7179 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen, 7180 emitEmptyBoundParameters); 7181 } 7182 7183 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 7184 CodeGenModule &CGM, StringRef ParentName, 7185 const OMPTargetParallelForDirective &S) { 7186 // Emit SPMD target parallel for region as a standalone region. 7187 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7188 emitTargetParallelForRegion(CGF, S, Action); 7189 }; 7190 llvm::Function *Fn; 7191 llvm::Constant *Addr; 7192 // Emit target region as a standalone region. 7193 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 7194 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 7195 assert(Fn && Addr && "Target device function emission failed."); 7196 } 7197 7198 void CodeGenFunction::EmitOMPTargetParallelForDirective( 7199 const OMPTargetParallelForDirective &S) { 7200 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7201 emitTargetParallelForRegion(CGF, S, Action); 7202 }; 7203 emitCommonOMPTargetDirective(*this, S, CodeGen); 7204 } 7205 7206 static void 7207 emitTargetParallelForSimdRegion(CodeGenFunction &CGF, 7208 const OMPTargetParallelForSimdDirective &S, 7209 PrePostActionTy &Action) { 7210 Action.Enter(CGF); 7211 // Emit directive as a combined directive that consists of two implicit 7212 // directives: 'parallel' with 'for' directive. 7213 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7214 Action.Enter(CGF); 7215 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 7216 emitDispatchForLoopBounds); 7217 }; 7218 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen, 7219 emitEmptyBoundParameters); 7220 } 7221 7222 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 7223 CodeGenModule &CGM, StringRef ParentName, 7224 const OMPTargetParallelForSimdDirective &S) { 7225 // Emit SPMD target parallel for region as a standalone region. 7226 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7227 emitTargetParallelForSimdRegion(CGF, S, Action); 7228 }; 7229 llvm::Function *Fn; 7230 llvm::Constant *Addr; 7231 // Emit target region as a standalone region. 7232 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 7233 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 7234 assert(Fn && Addr && "Target device function emission failed."); 7235 } 7236 7237 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective( 7238 const OMPTargetParallelForSimdDirective &S) { 7239 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7240 emitTargetParallelForSimdRegion(CGF, S, Action); 7241 }; 7242 emitCommonOMPTargetDirective(*this, S, CodeGen); 7243 } 7244 7245 /// Emit a helper variable and return corresponding lvalue. 7246 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, 7247 const ImplicitParamDecl *PVD, 7248 CodeGenFunction::OMPPrivateScope &Privates) { 7249 const auto *VDecl = cast<VarDecl>(Helper->getDecl()); 7250 Privates.addPrivate(VDecl, CGF.GetAddrOfLocalVar(PVD)); 7251 } 7252 7253 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) { 7254 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind())); 7255 // Emit outlined function for task construct. 7256 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop); 7257 Address CapturedStruct = Address::invalid(); 7258 { 7259 OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 7260 CapturedStruct = GenerateCapturedStmtArgument(*CS); 7261 } 7262 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 7263 const Expr *IfCond = nullptr; 7264 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 7265 if (C->getNameModifier() == OMPD_unknown || 7266 C->getNameModifier() == OMPD_taskloop) { 7267 IfCond = C->getCondition(); 7268 break; 7269 } 7270 } 7271 7272 OMPTaskDataTy Data; 7273 // Check if taskloop must be emitted without taskgroup. 7274 Data.Nogroup = S.getSingleClause<OMPNogroupClause>(); 7275 // TODO: Check if we should emit tied or untied task. 7276 Data.Tied = true; 7277 // Set scheduling for taskloop 7278 if (const auto *Clause = S.getSingleClause<OMPGrainsizeClause>()) { 7279 // grainsize clause 7280 Data.Schedule.setInt(/*IntVal=*/false); 7281 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize())); 7282 } else if (const auto *Clause = S.getSingleClause<OMPNumTasksClause>()) { 7283 // num_tasks clause 7284 Data.Schedule.setInt(/*IntVal=*/true); 7285 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks())); 7286 } 7287 7288 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) { 7289 // if (PreCond) { 7290 // for (IV in 0..LastIteration) BODY; 7291 // <Final counter/linear vars updates>; 7292 // } 7293 // 7294 7295 // Emit: if (PreCond) - begin. 7296 // If the condition constant folds and can be elided, avoid emitting the 7297 // whole loop. 7298 bool CondConstant; 7299 llvm::BasicBlock *ContBlock = nullptr; 7300 OMPLoopScope PreInitScope(CGF, S); 7301 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 7302 if (!CondConstant) 7303 return; 7304 } else { 7305 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then"); 7306 ContBlock = CGF.createBasicBlock("taskloop.if.end"); 7307 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 7308 CGF.getProfileCount(&S)); 7309 CGF.EmitBlock(ThenBlock); 7310 CGF.incrementProfileCounter(&S); 7311 } 7312 7313 (void)CGF.EmitOMPLinearClauseInit(S); 7314 7315 OMPPrivateScope LoopScope(CGF); 7316 // Emit helper vars inits. 7317 enum { LowerBound = 5, UpperBound, Stride, LastIter }; 7318 auto *I = CS->getCapturedDecl()->param_begin(); 7319 auto *LBP = std::next(I, LowerBound); 7320 auto *UBP = std::next(I, UpperBound); 7321 auto *STP = std::next(I, Stride); 7322 auto *LIP = std::next(I, LastIter); 7323 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP, 7324 LoopScope); 7325 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP, 7326 LoopScope); 7327 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope); 7328 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP, 7329 LoopScope); 7330 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 7331 CGF.EmitOMPLinearClause(S, LoopScope); 7332 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 7333 (void)LoopScope.Privatize(); 7334 // Emit the loop iteration variable. 7335 const Expr *IVExpr = S.getIterationVariable(); 7336 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 7337 CGF.EmitVarDecl(*IVDecl); 7338 CGF.EmitIgnoredExpr(S.getInit()); 7339 7340 // Emit the iterations count variable. 7341 // If it is not a variable, Sema decided to calculate iterations count on 7342 // each iteration (e.g., it is foldable into a constant). 7343 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 7344 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 7345 // Emit calculation of the iterations count. 7346 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 7347 } 7348 7349 { 7350 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 7351 emitCommonSimdLoop( 7352 CGF, S, 7353 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 7354 if (isOpenMPSimdDirective(S.getDirectiveKind())) 7355 CGF.EmitOMPSimdInit(S); 7356 }, 7357 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 7358 CGF.EmitOMPInnerLoop( 7359 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 7360 [&S](CodeGenFunction &CGF) { 7361 emitOMPLoopBodyWithStopPoint(CGF, S, 7362 CodeGenFunction::JumpDest()); 7363 }, 7364 [](CodeGenFunction &) {}); 7365 }); 7366 } 7367 // Emit: if (PreCond) - end. 7368 if (ContBlock) { 7369 CGF.EmitBranch(ContBlock); 7370 CGF.EmitBlock(ContBlock, true); 7371 } 7372 // Emit final copy of the lastprivate variables if IsLastIter != 0. 7373 if (HasLastprivateClause) { 7374 CGF.EmitOMPLastprivateClauseFinal( 7375 S, isOpenMPSimdDirective(S.getDirectiveKind()), 7376 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar( 7377 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 7378 (*LIP)->getType(), S.getBeginLoc()))); 7379 } 7380 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) { 7381 return CGF.Builder.CreateIsNotNull( 7382 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 7383 (*LIP)->getType(), S.getBeginLoc())); 7384 }); 7385 }; 7386 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 7387 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 7388 const OMPTaskDataTy &Data) { 7389 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond, 7390 &Data](CodeGenFunction &CGF, PrePostActionTy &) { 7391 OMPLoopScope PreInitScope(CGF, S); 7392 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S, 7393 OutlinedFn, SharedsTy, 7394 CapturedStruct, IfCond, Data); 7395 }; 7396 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop, 7397 CodeGen); 7398 }; 7399 if (Data.Nogroup) { 7400 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data); 7401 } else { 7402 CGM.getOpenMPRuntime().emitTaskgroupRegion( 7403 *this, 7404 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF, 7405 PrePostActionTy &Action) { 7406 Action.Enter(CGF); 7407 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, 7408 Data); 7409 }, 7410 S.getBeginLoc()); 7411 } 7412 } 7413 7414 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) { 7415 auto LPCRegion = 7416 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7417 EmitOMPTaskLoopBasedDirective(S); 7418 } 7419 7420 void CodeGenFunction::EmitOMPTaskLoopSimdDirective( 7421 const OMPTaskLoopSimdDirective &S) { 7422 auto LPCRegion = 7423 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7424 OMPLexicalScope Scope(*this, S); 7425 EmitOMPTaskLoopBasedDirective(S); 7426 } 7427 7428 void CodeGenFunction::EmitOMPMasterTaskLoopDirective( 7429 const OMPMasterTaskLoopDirective &S) { 7430 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7431 Action.Enter(CGF); 7432 EmitOMPTaskLoopBasedDirective(S); 7433 }; 7434 auto LPCRegion = 7435 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7436 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false); 7437 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 7438 } 7439 7440 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective( 7441 const OMPMasterTaskLoopSimdDirective &S) { 7442 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7443 Action.Enter(CGF); 7444 EmitOMPTaskLoopBasedDirective(S); 7445 }; 7446 auto LPCRegion = 7447 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7448 OMPLexicalScope Scope(*this, S); 7449 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 7450 } 7451 7452 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective( 7453 const OMPParallelMasterTaskLoopDirective &S) { 7454 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7455 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 7456 PrePostActionTy &Action) { 7457 Action.Enter(CGF); 7458 CGF.EmitOMPTaskLoopBasedDirective(S); 7459 }; 7460 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 7461 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 7462 S.getBeginLoc()); 7463 }; 7464 auto LPCRegion = 7465 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7466 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen, 7467 emitEmptyBoundParameters); 7468 } 7469 7470 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective( 7471 const OMPParallelMasterTaskLoopSimdDirective &S) { 7472 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7473 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 7474 PrePostActionTy &Action) { 7475 Action.Enter(CGF); 7476 CGF.EmitOMPTaskLoopBasedDirective(S); 7477 }; 7478 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 7479 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 7480 S.getBeginLoc()); 7481 }; 7482 auto LPCRegion = 7483 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 7484 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen, 7485 emitEmptyBoundParameters); 7486 } 7487 7488 // Generate the instructions for '#pragma omp target update' directive. 7489 void CodeGenFunction::EmitOMPTargetUpdateDirective( 7490 const OMPTargetUpdateDirective &S) { 7491 // If we don't have target devices, don't bother emitting the data mapping 7492 // code. 7493 if (CGM.getLangOpts().OMPTargetTriples.empty()) 7494 return; 7495 7496 // Check if we have any if clause associated with the directive. 7497 const Expr *IfCond = nullptr; 7498 if (const auto *C = S.getSingleClause<OMPIfClause>()) 7499 IfCond = C->getCondition(); 7500 7501 // Check if we have any device clause associated with the directive. 7502 const Expr *Device = nullptr; 7503 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 7504 Device = C->getDevice(); 7505 7506 OMPLexicalScope Scope(*this, S, OMPD_task); 7507 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 7508 } 7509 7510 void CodeGenFunction::EmitOMPGenericLoopDirective( 7511 const OMPGenericLoopDirective &S) { 7512 // Unimplemented, just inline the underlying statement for now. 7513 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 7514 CGF.EmitStmt(cast<CapturedStmt>(S.getAssociatedStmt())->getCapturedStmt()); 7515 }; 7516 OMPLexicalScope Scope(*this, S, OMPD_unknown); 7517 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_loop, CodeGen); 7518 } 7519 7520 void CodeGenFunction::EmitSimpleOMPExecutableDirective( 7521 const OMPExecutableDirective &D) { 7522 if (const auto *SD = dyn_cast<OMPScanDirective>(&D)) { 7523 EmitOMPScanDirective(*SD); 7524 return; 7525 } 7526 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt()) 7527 return; 7528 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) { 7529 OMPPrivateScope GlobalsScope(CGF); 7530 if (isOpenMPTaskingDirective(D.getDirectiveKind())) { 7531 // Capture global firstprivates to avoid crash. 7532 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 7533 for (const Expr *Ref : C->varlists()) { 7534 const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 7535 if (!DRE) 7536 continue; 7537 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 7538 if (!VD || VD->hasLocalStorage()) 7539 continue; 7540 if (!CGF.LocalDeclMap.count(VD)) { 7541 LValue GlobLVal = CGF.EmitLValue(Ref); 7542 GlobalsScope.addPrivate(VD, GlobLVal.getAddress(CGF)); 7543 } 7544 } 7545 } 7546 } 7547 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 7548 (void)GlobalsScope.Privatize(); 7549 ParentLoopDirectiveForScanRegion ScanRegion(CGF, D); 7550 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action); 7551 } else { 7552 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) { 7553 for (const Expr *E : LD->counters()) { 7554 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 7555 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) { 7556 LValue GlobLVal = CGF.EmitLValue(E); 7557 GlobalsScope.addPrivate(VD, GlobLVal.getAddress(CGF)); 7558 } 7559 if (isa<OMPCapturedExprDecl>(VD)) { 7560 // Emit only those that were not explicitly referenced in clauses. 7561 if (!CGF.LocalDeclMap.count(VD)) 7562 CGF.EmitVarDecl(*VD); 7563 } 7564 } 7565 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) { 7566 if (!C->getNumForLoops()) 7567 continue; 7568 for (unsigned I = LD->getLoopsNumber(), 7569 E = C->getLoopNumIterations().size(); 7570 I < E; ++I) { 7571 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>( 7572 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) { 7573 // Emit only those that were not explicitly referenced in clauses. 7574 if (!CGF.LocalDeclMap.count(VD)) 7575 CGF.EmitVarDecl(*VD); 7576 } 7577 } 7578 } 7579 } 7580 (void)GlobalsScope.Privatize(); 7581 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt()); 7582 } 7583 }; 7584 if (D.getDirectiveKind() == OMPD_atomic || 7585 D.getDirectiveKind() == OMPD_critical || 7586 D.getDirectiveKind() == OMPD_section || 7587 D.getDirectiveKind() == OMPD_master || 7588 D.getDirectiveKind() == OMPD_masked) { 7589 EmitStmt(D.getAssociatedStmt()); 7590 } else { 7591 auto LPCRegion = 7592 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D); 7593 OMPSimdLexicalScope Scope(*this, D); 7594 CGM.getOpenMPRuntime().emitInlinedDirective( 7595 *this, 7596 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd 7597 : D.getDirectiveKind(), 7598 CodeGen); 7599 } 7600 // Check for outer lastprivate conditional update. 7601 checkForLastprivateConditionalUpdate(*this, D); 7602 } 7603