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/Basic/OpenMPKinds.h" 25 #include "clang/Basic/PrettyStackTrace.h" 26 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 27 #include "llvm/IR/Instructions.h" 28 #include "llvm/Support/AtomicOrdering.h" 29 using namespace clang; 30 using namespace CodeGen; 31 using namespace llvm::omp; 32 33 namespace { 34 /// Lexical scope for OpenMP executable constructs, that handles correct codegen 35 /// for captured expressions. 36 class OMPLexicalScope : public CodeGenFunction::LexicalScope { 37 void emitPreInitStmt(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 38 for (const auto *C : S.clauses()) { 39 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 40 if (const auto *PreInit = 41 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 42 for (const auto *I : PreInit->decls()) { 43 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 44 CGF.EmitVarDecl(cast<VarDecl>(*I)); 45 } else { 46 CodeGenFunction::AutoVarEmission Emission = 47 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 48 CGF.EmitAutoVarCleanups(Emission); 49 } 50 } 51 } 52 } 53 } 54 } 55 CodeGenFunction::OMPPrivateScope InlinedShareds; 56 57 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 58 return CGF.LambdaCaptureFields.lookup(VD) || 59 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 60 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl)); 61 } 62 63 public: 64 OMPLexicalScope( 65 CodeGenFunction &CGF, const OMPExecutableDirective &S, 66 const llvm::Optional<OpenMPDirectiveKind> CapturedRegion = llvm::None, 67 const bool EmitPreInitStmt = true) 68 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 69 InlinedShareds(CGF) { 70 if (EmitPreInitStmt) 71 emitPreInitStmt(CGF, S); 72 if (!CapturedRegion.hasValue()) 73 return; 74 assert(S.hasAssociatedStmt() && 75 "Expected associated statement for inlined directive."); 76 const CapturedStmt *CS = S.getCapturedStmt(*CapturedRegion); 77 for (const auto &C : CS->captures()) { 78 if (C.capturesVariable() || C.capturesVariableByCopy()) { 79 auto *VD = C.getCapturedVar(); 80 assert(VD == VD->getCanonicalDecl() && 81 "Canonical decl must be captured."); 82 DeclRefExpr DRE( 83 CGF.getContext(), const_cast<VarDecl *>(VD), 84 isCapturedVar(CGF, VD) || (CGF.CapturedStmtInfo && 85 InlinedShareds.isGlobalVarCaptured(VD)), 86 VD->getType().getNonReferenceType(), VK_LValue, C.getLocation()); 87 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address { 88 return CGF.EmitLValue(&DRE).getAddress(CGF); 89 }); 90 } 91 } 92 (void)InlinedShareds.Privatize(); 93 } 94 }; 95 96 /// Lexical scope for OpenMP parallel construct, that handles correct codegen 97 /// for captured expressions. 98 class OMPParallelScope final : public OMPLexicalScope { 99 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 100 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 101 return !(isOpenMPTargetExecutionDirective(Kind) || 102 isOpenMPLoopBoundSharingDirective(Kind)) && 103 isOpenMPParallelDirective(Kind); 104 } 105 106 public: 107 OMPParallelScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 108 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 109 EmitPreInitStmt(S)) {} 110 }; 111 112 /// Lexical scope for OpenMP teams construct, that handles correct codegen 113 /// for captured expressions. 114 class OMPTeamsScope final : public OMPLexicalScope { 115 bool EmitPreInitStmt(const OMPExecutableDirective &S) { 116 OpenMPDirectiveKind Kind = S.getDirectiveKind(); 117 return !isOpenMPTargetExecutionDirective(Kind) && 118 isOpenMPTeamsDirective(Kind); 119 } 120 121 public: 122 OMPTeamsScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 123 : OMPLexicalScope(CGF, S, /*CapturedRegion=*/llvm::None, 124 EmitPreInitStmt(S)) {} 125 }; 126 127 /// Private scope for OpenMP loop-based directives, that supports capturing 128 /// of used expression from loop statement. 129 class OMPLoopScope : public CodeGenFunction::RunCleanupsScope { 130 void emitPreInitStmt(CodeGenFunction &CGF, const OMPLoopDirective &S) { 131 CodeGenFunction::OMPMapVars PreCondVars; 132 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 133 for (const auto *E : S.counters()) { 134 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 135 EmittedAsPrivate.insert(VD->getCanonicalDecl()); 136 (void)PreCondVars.setVarAddr( 137 CGF, VD, CGF.CreateMemTemp(VD->getType().getNonReferenceType())); 138 } 139 // Mark private vars as undefs. 140 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 141 for (const Expr *IRef : C->varlists()) { 142 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(IRef)->getDecl()); 143 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 144 (void)PreCondVars.setVarAddr( 145 CGF, OrigVD, 146 Address(llvm::UndefValue::get( 147 CGF.ConvertTypeForMem(CGF.getContext().getPointerType( 148 OrigVD->getType().getNonReferenceType()))), 149 CGF.getContext().getDeclAlign(OrigVD))); 150 } 151 } 152 } 153 (void)PreCondVars.apply(CGF); 154 // Emit init, __range and __end variables for C++ range loops. 155 const Stmt *Body = 156 S.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); 157 for (unsigned Cnt = 0; Cnt < S.getCollapsedNumber(); ++Cnt) { 158 Body = OMPLoopDirective::tryToFindNextInnerLoop( 159 Body, /*TryImperfectlyNestedLoops=*/true); 160 if (auto *For = dyn_cast<ForStmt>(Body)) { 161 Body = For->getBody(); 162 } else { 163 assert(isa<CXXForRangeStmt>(Body) && 164 "Expected canonical for loop or range-based for loop."); 165 auto *CXXFor = cast<CXXForRangeStmt>(Body); 166 if (const Stmt *Init = CXXFor->getInit()) 167 CGF.EmitStmt(Init); 168 CGF.EmitStmt(CXXFor->getRangeStmt()); 169 CGF.EmitStmt(CXXFor->getEndStmt()); 170 Body = CXXFor->getBody(); 171 } 172 } 173 if (const auto *PreInits = cast_or_null<DeclStmt>(S.getPreInits())) { 174 for (const auto *I : PreInits->decls()) 175 CGF.EmitVarDecl(cast<VarDecl>(*I)); 176 } 177 PreCondVars.restore(CGF); 178 } 179 180 public: 181 OMPLoopScope(CodeGenFunction &CGF, const OMPLoopDirective &S) 182 : CodeGenFunction::RunCleanupsScope(CGF) { 183 emitPreInitStmt(CGF, S); 184 } 185 }; 186 187 class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope { 188 CodeGenFunction::OMPPrivateScope InlinedShareds; 189 190 static bool isCapturedVar(CodeGenFunction &CGF, const VarDecl *VD) { 191 return CGF.LambdaCaptureFields.lookup(VD) || 192 (CGF.CapturedStmtInfo && CGF.CapturedStmtInfo->lookup(VD)) || 193 (CGF.CurCodeDecl && isa<BlockDecl>(CGF.CurCodeDecl) && 194 cast<BlockDecl>(CGF.CurCodeDecl)->capturesVariable(VD)); 195 } 196 197 public: 198 OMPSimdLexicalScope(CodeGenFunction &CGF, const OMPExecutableDirective &S) 199 : CodeGenFunction::LexicalScope(CGF, S.getSourceRange()), 200 InlinedShareds(CGF) { 201 for (const auto *C : S.clauses()) { 202 if (const auto *CPI = OMPClauseWithPreInit::get(C)) { 203 if (const auto *PreInit = 204 cast_or_null<DeclStmt>(CPI->getPreInitStmt())) { 205 for (const auto *I : PreInit->decls()) { 206 if (!I->hasAttr<OMPCaptureNoInitAttr>()) { 207 CGF.EmitVarDecl(cast<VarDecl>(*I)); 208 } else { 209 CodeGenFunction::AutoVarEmission Emission = 210 CGF.EmitAutoVarAlloca(cast<VarDecl>(*I)); 211 CGF.EmitAutoVarCleanups(Emission); 212 } 213 } 214 } 215 } else if (const auto *UDP = dyn_cast<OMPUseDevicePtrClause>(C)) { 216 for (const Expr *E : UDP->varlists()) { 217 const Decl *D = cast<DeclRefExpr>(E)->getDecl(); 218 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(D)) 219 CGF.EmitVarDecl(*OED); 220 } 221 } 222 } 223 if (!isOpenMPSimdDirective(S.getDirectiveKind())) 224 CGF.EmitOMPPrivateClause(S, InlinedShareds); 225 if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) { 226 if (const Expr *E = TG->getReductionRef()) 227 CGF.EmitVarDecl(*cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())); 228 } 229 const auto *CS = cast_or_null<CapturedStmt>(S.getAssociatedStmt()); 230 while (CS) { 231 for (auto &C : CS->captures()) { 232 if (C.capturesVariable() || C.capturesVariableByCopy()) { 233 auto *VD = C.getCapturedVar(); 234 assert(VD == VD->getCanonicalDecl() && 235 "Canonical decl must be captured."); 236 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(VD), 237 isCapturedVar(CGF, VD) || 238 (CGF.CapturedStmtInfo && 239 InlinedShareds.isGlobalVarCaptured(VD)), 240 VD->getType().getNonReferenceType(), VK_LValue, 241 C.getLocation()); 242 InlinedShareds.addPrivate(VD, [&CGF, &DRE]() -> Address { 243 return CGF.EmitLValue(&DRE).getAddress(CGF); 244 }); 245 } 246 } 247 CS = dyn_cast<CapturedStmt>(CS->getCapturedStmt()); 248 } 249 (void)InlinedShareds.Privatize(); 250 } 251 }; 252 253 } // namespace 254 255 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 256 const OMPExecutableDirective &S, 257 const RegionCodeGenTy &CodeGen); 258 259 LValue CodeGenFunction::EmitOMPSharedLValue(const Expr *E) { 260 if (const auto *OrigDRE = dyn_cast<DeclRefExpr>(E)) { 261 if (const auto *OrigVD = dyn_cast<VarDecl>(OrigDRE->getDecl())) { 262 OrigVD = OrigVD->getCanonicalDecl(); 263 bool IsCaptured = 264 LambdaCaptureFields.lookup(OrigVD) || 265 (CapturedStmtInfo && CapturedStmtInfo->lookup(OrigVD)) || 266 (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)); 267 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), IsCaptured, 268 OrigDRE->getType(), VK_LValue, OrigDRE->getExprLoc()); 269 return EmitLValue(&DRE); 270 } 271 } 272 return EmitLValue(E); 273 } 274 275 llvm::Value *CodeGenFunction::getTypeSize(QualType Ty) { 276 ASTContext &C = getContext(); 277 llvm::Value *Size = nullptr; 278 auto SizeInChars = C.getTypeSizeInChars(Ty); 279 if (SizeInChars.isZero()) { 280 // getTypeSizeInChars() returns 0 for a VLA. 281 while (const VariableArrayType *VAT = C.getAsVariableArrayType(Ty)) { 282 VlaSizePair VlaSize = getVLASize(VAT); 283 Ty = VlaSize.Type; 284 Size = Size ? Builder.CreateNUWMul(Size, VlaSize.NumElts) 285 : VlaSize.NumElts; 286 } 287 SizeInChars = C.getTypeSizeInChars(Ty); 288 if (SizeInChars.isZero()) 289 return llvm::ConstantInt::get(SizeTy, /*V=*/0); 290 return Builder.CreateNUWMul(Size, CGM.getSize(SizeInChars)); 291 } 292 return CGM.getSize(SizeInChars); 293 } 294 295 void CodeGenFunction::GenerateOpenMPCapturedVars( 296 const CapturedStmt &S, SmallVectorImpl<llvm::Value *> &CapturedVars) { 297 const RecordDecl *RD = S.getCapturedRecordDecl(); 298 auto CurField = RD->field_begin(); 299 auto CurCap = S.captures().begin(); 300 for (CapturedStmt::const_capture_init_iterator I = S.capture_init_begin(), 301 E = S.capture_init_end(); 302 I != E; ++I, ++CurField, ++CurCap) { 303 if (CurField->hasCapturedVLAType()) { 304 const VariableArrayType *VAT = CurField->getCapturedVLAType(); 305 llvm::Value *Val = VLASizeMap[VAT->getSizeExpr()]; 306 CapturedVars.push_back(Val); 307 } else if (CurCap->capturesThis()) { 308 CapturedVars.push_back(CXXThisValue); 309 } else if (CurCap->capturesVariableByCopy()) { 310 llvm::Value *CV = EmitLoadOfScalar(EmitLValue(*I), CurCap->getLocation()); 311 312 // If the field is not a pointer, we need to save the actual value 313 // and load it as a void pointer. 314 if (!CurField->getType()->isAnyPointerType()) { 315 ASTContext &Ctx = getContext(); 316 Address DstAddr = CreateMemTemp( 317 Ctx.getUIntPtrType(), 318 Twine(CurCap->getCapturedVar()->getName(), ".casted")); 319 LValue DstLV = MakeAddrLValue(DstAddr, Ctx.getUIntPtrType()); 320 321 llvm::Value *SrcAddrVal = EmitScalarConversion( 322 DstAddr.getPointer(), Ctx.getPointerType(Ctx.getUIntPtrType()), 323 Ctx.getPointerType(CurField->getType()), CurCap->getLocation()); 324 LValue SrcLV = 325 MakeNaturalAlignAddrLValue(SrcAddrVal, CurField->getType()); 326 327 // Store the value using the source type pointer. 328 EmitStoreThroughLValue(RValue::get(CV), SrcLV); 329 330 // Load the value using the destination type pointer. 331 CV = EmitLoadOfScalar(DstLV, CurCap->getLocation()); 332 } 333 CapturedVars.push_back(CV); 334 } else { 335 assert(CurCap->capturesVariable() && "Expected capture by reference."); 336 CapturedVars.push_back(EmitLValue(*I).getAddress(*this).getPointer()); 337 } 338 } 339 } 340 341 static Address castValueFromUintptr(CodeGenFunction &CGF, SourceLocation Loc, 342 QualType DstType, StringRef Name, 343 LValue AddrLV) { 344 ASTContext &Ctx = CGF.getContext(); 345 346 llvm::Value *CastedPtr = CGF.EmitScalarConversion( 347 AddrLV.getAddress(CGF).getPointer(), Ctx.getUIntPtrType(), 348 Ctx.getPointerType(DstType), Loc); 349 Address TmpAddr = 350 CGF.MakeNaturalAlignAddrLValue(CastedPtr, Ctx.getPointerType(DstType)) 351 .getAddress(CGF); 352 return TmpAddr; 353 } 354 355 static QualType getCanonicalParamType(ASTContext &C, QualType T) { 356 if (T->isLValueReferenceType()) 357 return C.getLValueReferenceType( 358 getCanonicalParamType(C, T.getNonReferenceType()), 359 /*SpelledAsLValue=*/false); 360 if (T->isPointerType()) 361 return C.getPointerType(getCanonicalParamType(C, T->getPointeeType())); 362 if (const ArrayType *A = T->getAsArrayTypeUnsafe()) { 363 if (const auto *VLA = dyn_cast<VariableArrayType>(A)) 364 return getCanonicalParamType(C, VLA->getElementType()); 365 if (!A->isVariablyModifiedType()) 366 return C.getCanonicalType(T); 367 } 368 return C.getCanonicalParamType(T); 369 } 370 371 namespace { 372 /// Contains required data for proper outlined function codegen. 373 struct FunctionOptions { 374 /// Captured statement for which the function is generated. 375 const CapturedStmt *S = nullptr; 376 /// true if cast to/from UIntPtr is required for variables captured by 377 /// value. 378 const bool UIntPtrCastRequired = true; 379 /// true if only casted arguments must be registered as local args or VLA 380 /// sizes. 381 const bool RegisterCastedArgsOnly = false; 382 /// Name of the generated function. 383 const StringRef FunctionName; 384 /// Location of the non-debug version of the outlined function. 385 SourceLocation Loc; 386 explicit FunctionOptions(const CapturedStmt *S, bool UIntPtrCastRequired, 387 bool RegisterCastedArgsOnly, StringRef FunctionName, 388 SourceLocation Loc) 389 : S(S), UIntPtrCastRequired(UIntPtrCastRequired), 390 RegisterCastedArgsOnly(UIntPtrCastRequired && RegisterCastedArgsOnly), 391 FunctionName(FunctionName), Loc(Loc) {} 392 }; 393 } // namespace 394 395 static llvm::Function *emitOutlinedFunctionPrologue( 396 CodeGenFunction &CGF, FunctionArgList &Args, 397 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> 398 &LocalAddrs, 399 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> 400 &VLASizes, 401 llvm::Value *&CXXThisValue, const FunctionOptions &FO) { 402 const CapturedDecl *CD = FO.S->getCapturedDecl(); 403 const RecordDecl *RD = FO.S->getCapturedRecordDecl(); 404 assert(CD->hasBody() && "missing CapturedDecl body"); 405 406 CXXThisValue = nullptr; 407 // Build the argument list. 408 CodeGenModule &CGM = CGF.CGM; 409 ASTContext &Ctx = CGM.getContext(); 410 FunctionArgList TargetArgs; 411 Args.append(CD->param_begin(), 412 std::next(CD->param_begin(), CD->getContextParamPosition())); 413 TargetArgs.append( 414 CD->param_begin(), 415 std::next(CD->param_begin(), CD->getContextParamPosition())); 416 auto I = FO.S->captures().begin(); 417 FunctionDecl *DebugFunctionDecl = nullptr; 418 if (!FO.UIntPtrCastRequired) { 419 FunctionProtoType::ExtProtoInfo EPI; 420 QualType FunctionTy = Ctx.getFunctionType(Ctx.VoidTy, llvm::None, EPI); 421 DebugFunctionDecl = FunctionDecl::Create( 422 Ctx, Ctx.getTranslationUnitDecl(), FO.S->getBeginLoc(), 423 SourceLocation(), DeclarationName(), FunctionTy, 424 Ctx.getTrivialTypeSourceInfo(FunctionTy), SC_Static, 425 /*isInlineSpecified=*/false, /*hasWrittenPrototype=*/false); 426 } 427 for (const FieldDecl *FD : RD->fields()) { 428 QualType ArgType = FD->getType(); 429 IdentifierInfo *II = nullptr; 430 VarDecl *CapVar = nullptr; 431 432 // If this is a capture by copy and the type is not a pointer, the outlined 433 // function argument type should be uintptr and the value properly casted to 434 // uintptr. This is necessary given that the runtime library is only able to 435 // deal with pointers. We can pass in the same way the VLA type sizes to the 436 // outlined function. 437 if (FO.UIntPtrCastRequired && 438 ((I->capturesVariableByCopy() && !ArgType->isAnyPointerType()) || 439 I->capturesVariableArrayType())) 440 ArgType = Ctx.getUIntPtrType(); 441 442 if (I->capturesVariable() || I->capturesVariableByCopy()) { 443 CapVar = I->getCapturedVar(); 444 II = CapVar->getIdentifier(); 445 } else if (I->capturesThis()) { 446 II = &Ctx.Idents.get("this"); 447 } else { 448 assert(I->capturesVariableArrayType()); 449 II = &Ctx.Idents.get("vla"); 450 } 451 if (ArgType->isVariablyModifiedType()) 452 ArgType = getCanonicalParamType(Ctx, ArgType); 453 VarDecl *Arg; 454 if (DebugFunctionDecl && (CapVar || I->capturesThis())) { 455 Arg = ParmVarDecl::Create( 456 Ctx, DebugFunctionDecl, 457 CapVar ? CapVar->getBeginLoc() : FD->getBeginLoc(), 458 CapVar ? CapVar->getLocation() : FD->getLocation(), II, ArgType, 459 /*TInfo=*/nullptr, SC_None, /*DefArg=*/nullptr); 460 } else { 461 Arg = ImplicitParamDecl::Create(Ctx, /*DC=*/nullptr, FD->getLocation(), 462 II, ArgType, ImplicitParamDecl::Other); 463 } 464 Args.emplace_back(Arg); 465 // Do not cast arguments if we emit function with non-original types. 466 TargetArgs.emplace_back( 467 FO.UIntPtrCastRequired 468 ? Arg 469 : CGM.getOpenMPRuntime().translateParameter(FD, Arg)); 470 ++I; 471 } 472 Args.append( 473 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 474 CD->param_end()); 475 TargetArgs.append( 476 std::next(CD->param_begin(), CD->getContextParamPosition() + 1), 477 CD->param_end()); 478 479 // Create the function declaration. 480 const CGFunctionInfo &FuncInfo = 481 CGM.getTypes().arrangeBuiltinFunctionDeclaration(Ctx.VoidTy, TargetArgs); 482 llvm::FunctionType *FuncLLVMTy = CGM.getTypes().GetFunctionType(FuncInfo); 483 484 auto *F = 485 llvm::Function::Create(FuncLLVMTy, llvm::GlobalValue::InternalLinkage, 486 FO.FunctionName, &CGM.getModule()); 487 CGM.SetInternalFunctionAttributes(CD, F, FuncInfo); 488 if (CD->isNothrow()) 489 F->setDoesNotThrow(); 490 F->setDoesNotRecurse(); 491 492 // Generate the function. 493 CGF.StartFunction(CD, Ctx.VoidTy, F, FuncInfo, TargetArgs, 494 FO.UIntPtrCastRequired ? FO.Loc : FO.S->getBeginLoc(), 495 FO.UIntPtrCastRequired ? FO.Loc 496 : CD->getBody()->getBeginLoc()); 497 unsigned Cnt = CD->getContextParamPosition(); 498 I = FO.S->captures().begin(); 499 for (const FieldDecl *FD : RD->fields()) { 500 // Do not map arguments if we emit function with non-original types. 501 Address LocalAddr(Address::invalid()); 502 if (!FO.UIntPtrCastRequired && Args[Cnt] != TargetArgs[Cnt]) { 503 LocalAddr = CGM.getOpenMPRuntime().getParameterAddress(CGF, Args[Cnt], 504 TargetArgs[Cnt]); 505 } else { 506 LocalAddr = CGF.GetAddrOfLocalVar(Args[Cnt]); 507 } 508 // If we are capturing a pointer by copy we don't need to do anything, just 509 // use the value that we get from the arguments. 510 if (I->capturesVariableByCopy() && FD->getType()->isAnyPointerType()) { 511 const VarDecl *CurVD = I->getCapturedVar(); 512 if (!FO.RegisterCastedArgsOnly) 513 LocalAddrs.insert({Args[Cnt], {CurVD, LocalAddr}}); 514 ++Cnt; 515 ++I; 516 continue; 517 } 518 519 LValue ArgLVal = CGF.MakeAddrLValue(LocalAddr, Args[Cnt]->getType(), 520 AlignmentSource::Decl); 521 if (FD->hasCapturedVLAType()) { 522 if (FO.UIntPtrCastRequired) { 523 ArgLVal = CGF.MakeAddrLValue( 524 castValueFromUintptr(CGF, I->getLocation(), FD->getType(), 525 Args[Cnt]->getName(), ArgLVal), 526 FD->getType(), AlignmentSource::Decl); 527 } 528 llvm::Value *ExprArg = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 529 const VariableArrayType *VAT = FD->getCapturedVLAType(); 530 VLASizes.try_emplace(Args[Cnt], VAT->getSizeExpr(), ExprArg); 531 } else if (I->capturesVariable()) { 532 const VarDecl *Var = I->getCapturedVar(); 533 QualType VarTy = Var->getType(); 534 Address ArgAddr = ArgLVal.getAddress(CGF); 535 if (ArgLVal.getType()->isLValueReferenceType()) { 536 ArgAddr = CGF.EmitLoadOfReference(ArgLVal); 537 } else if (!VarTy->isVariablyModifiedType() || !VarTy->isPointerType()) { 538 assert(ArgLVal.getType()->isPointerType()); 539 ArgAddr = CGF.EmitLoadOfPointer( 540 ArgAddr, ArgLVal.getType()->castAs<PointerType>()); 541 } 542 if (!FO.RegisterCastedArgsOnly) { 543 LocalAddrs.insert( 544 {Args[Cnt], 545 {Var, Address(ArgAddr.getPointer(), Ctx.getDeclAlign(Var))}}); 546 } 547 } else if (I->capturesVariableByCopy()) { 548 assert(!FD->getType()->isAnyPointerType() && 549 "Not expecting a captured pointer."); 550 const VarDecl *Var = I->getCapturedVar(); 551 LocalAddrs.insert({Args[Cnt], 552 {Var, FO.UIntPtrCastRequired 553 ? castValueFromUintptr( 554 CGF, I->getLocation(), FD->getType(), 555 Args[Cnt]->getName(), ArgLVal) 556 : ArgLVal.getAddress(CGF)}}); 557 } else { 558 // If 'this' is captured, load it into CXXThisValue. 559 assert(I->capturesThis()); 560 CXXThisValue = CGF.EmitLoadOfScalar(ArgLVal, I->getLocation()); 561 LocalAddrs.insert({Args[Cnt], {nullptr, ArgLVal.getAddress(CGF)}}); 562 } 563 ++Cnt; 564 ++I; 565 } 566 567 return F; 568 } 569 570 llvm::Function * 571 CodeGenFunction::GenerateOpenMPCapturedStmtFunction(const CapturedStmt &S, 572 SourceLocation Loc) { 573 assert( 574 CapturedStmtInfo && 575 "CapturedStmtInfo should be set when generating the captured function"); 576 const CapturedDecl *CD = S.getCapturedDecl(); 577 // Build the argument list. 578 bool NeedWrapperFunction = 579 getDebugInfo() && CGM.getCodeGenOpts().hasReducedDebugInfo(); 580 FunctionArgList Args; 581 llvm::MapVector<const Decl *, std::pair<const VarDecl *, Address>> LocalAddrs; 582 llvm::DenseMap<const Decl *, std::pair<const Expr *, llvm::Value *>> VLASizes; 583 SmallString<256> Buffer; 584 llvm::raw_svector_ostream Out(Buffer); 585 Out << CapturedStmtInfo->getHelperName(); 586 if (NeedWrapperFunction) 587 Out << "_debug__"; 588 FunctionOptions FO(&S, !NeedWrapperFunction, /*RegisterCastedArgsOnly=*/false, 589 Out.str(), Loc); 590 llvm::Function *F = emitOutlinedFunctionPrologue(*this, Args, LocalAddrs, 591 VLASizes, CXXThisValue, FO); 592 CodeGenFunction::OMPPrivateScope LocalScope(*this); 593 for (const auto &LocalAddrPair : LocalAddrs) { 594 if (LocalAddrPair.second.first) { 595 LocalScope.addPrivate(LocalAddrPair.second.first, [&LocalAddrPair]() { 596 return LocalAddrPair.second.second; 597 }); 598 } 599 } 600 (void)LocalScope.Privatize(); 601 for (const auto &VLASizePair : VLASizes) 602 VLASizeMap[VLASizePair.second.first] = VLASizePair.second.second; 603 PGO.assignRegionCounters(GlobalDecl(CD), F); 604 CapturedStmtInfo->EmitBody(*this, CD->getBody()); 605 (void)LocalScope.ForceCleanup(); 606 FinishFunction(CD->getBodyRBrace()); 607 if (!NeedWrapperFunction) 608 return F; 609 610 FunctionOptions WrapperFO(&S, /*UIntPtrCastRequired=*/true, 611 /*RegisterCastedArgsOnly=*/true, 612 CapturedStmtInfo->getHelperName(), Loc); 613 CodeGenFunction WrapperCGF(CGM, /*suppressNewContext=*/true); 614 WrapperCGF.CapturedStmtInfo = CapturedStmtInfo; 615 Args.clear(); 616 LocalAddrs.clear(); 617 VLASizes.clear(); 618 llvm::Function *WrapperF = 619 emitOutlinedFunctionPrologue(WrapperCGF, Args, LocalAddrs, VLASizes, 620 WrapperCGF.CXXThisValue, WrapperFO); 621 llvm::SmallVector<llvm::Value *, 4> CallArgs; 622 for (const auto *Arg : Args) { 623 llvm::Value *CallArg; 624 auto I = LocalAddrs.find(Arg); 625 if (I != LocalAddrs.end()) { 626 LValue LV = WrapperCGF.MakeAddrLValue( 627 I->second.second, 628 I->second.first ? I->second.first->getType() : Arg->getType(), 629 AlignmentSource::Decl); 630 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 631 } else { 632 auto EI = VLASizes.find(Arg); 633 if (EI != VLASizes.end()) { 634 CallArg = EI->second.second; 635 } else { 636 LValue LV = WrapperCGF.MakeAddrLValue(WrapperCGF.GetAddrOfLocalVar(Arg), 637 Arg->getType(), 638 AlignmentSource::Decl); 639 CallArg = WrapperCGF.EmitLoadOfScalar(LV, S.getBeginLoc()); 640 } 641 } 642 CallArgs.emplace_back(WrapperCGF.EmitFromMemory(CallArg, Arg->getType())); 643 } 644 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(WrapperCGF, Loc, F, CallArgs); 645 WrapperCGF.FinishFunction(); 646 return WrapperF; 647 } 648 649 //===----------------------------------------------------------------------===// 650 // OpenMP Directive Emission 651 //===----------------------------------------------------------------------===// 652 void CodeGenFunction::EmitOMPAggregateAssign( 653 Address DestAddr, Address SrcAddr, QualType OriginalType, 654 const llvm::function_ref<void(Address, Address)> CopyGen) { 655 // Perform element-by-element initialization. 656 QualType ElementTy; 657 658 // Drill down to the base element type on both arrays. 659 const ArrayType *ArrayTy = OriginalType->getAsArrayTypeUnsafe(); 660 llvm::Value *NumElements = emitArrayLength(ArrayTy, ElementTy, DestAddr); 661 SrcAddr = Builder.CreateElementBitCast(SrcAddr, DestAddr.getElementType()); 662 663 llvm::Value *SrcBegin = SrcAddr.getPointer(); 664 llvm::Value *DestBegin = DestAddr.getPointer(); 665 // Cast from pointer to array type to pointer to single element. 666 llvm::Value *DestEnd = Builder.CreateGEP(DestBegin, NumElements); 667 // The basic structure here is a while-do loop. 668 llvm::BasicBlock *BodyBB = createBasicBlock("omp.arraycpy.body"); 669 llvm::BasicBlock *DoneBB = createBasicBlock("omp.arraycpy.done"); 670 llvm::Value *IsEmpty = 671 Builder.CreateICmpEQ(DestBegin, DestEnd, "omp.arraycpy.isempty"); 672 Builder.CreateCondBr(IsEmpty, DoneBB, BodyBB); 673 674 // Enter the loop body, making that address the current address. 675 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 676 EmitBlock(BodyBB); 677 678 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementTy); 679 680 llvm::PHINode *SrcElementPHI = 681 Builder.CreatePHI(SrcBegin->getType(), 2, "omp.arraycpy.srcElementPast"); 682 SrcElementPHI->addIncoming(SrcBegin, EntryBB); 683 Address SrcElementCurrent = 684 Address(SrcElementPHI, 685 SrcAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 686 687 llvm::PHINode *DestElementPHI = 688 Builder.CreatePHI(DestBegin->getType(), 2, "omp.arraycpy.destElementPast"); 689 DestElementPHI->addIncoming(DestBegin, EntryBB); 690 Address DestElementCurrent = 691 Address(DestElementPHI, 692 DestAddr.getAlignment().alignmentOfArrayElement(ElementSize)); 693 694 // Emit copy. 695 CopyGen(DestElementCurrent, SrcElementCurrent); 696 697 // Shift the address forward by one element. 698 llvm::Value *DestElementNext = Builder.CreateConstGEP1_32( 699 DestElementPHI, /*Idx0=*/1, "omp.arraycpy.dest.element"); 700 llvm::Value *SrcElementNext = Builder.CreateConstGEP1_32( 701 SrcElementPHI, /*Idx0=*/1, "omp.arraycpy.src.element"); 702 // Check whether we've reached the end. 703 llvm::Value *Done = 704 Builder.CreateICmpEQ(DestElementNext, DestEnd, "omp.arraycpy.done"); 705 Builder.CreateCondBr(Done, DoneBB, BodyBB); 706 DestElementPHI->addIncoming(DestElementNext, Builder.GetInsertBlock()); 707 SrcElementPHI->addIncoming(SrcElementNext, Builder.GetInsertBlock()); 708 709 // Done. 710 EmitBlock(DoneBB, /*IsFinished=*/true); 711 } 712 713 void CodeGenFunction::EmitOMPCopy(QualType OriginalType, Address DestAddr, 714 Address SrcAddr, const VarDecl *DestVD, 715 const VarDecl *SrcVD, const Expr *Copy) { 716 if (OriginalType->isArrayType()) { 717 const auto *BO = dyn_cast<BinaryOperator>(Copy); 718 if (BO && BO->getOpcode() == BO_Assign) { 719 // Perform simple memcpy for simple copying. 720 LValue Dest = MakeAddrLValue(DestAddr, OriginalType); 721 LValue Src = MakeAddrLValue(SrcAddr, OriginalType); 722 EmitAggregateAssign(Dest, Src, OriginalType); 723 } else { 724 // For arrays with complex element types perform element by element 725 // copying. 726 EmitOMPAggregateAssign( 727 DestAddr, SrcAddr, OriginalType, 728 [this, Copy, SrcVD, DestVD](Address DestElement, Address SrcElement) { 729 // Working with the single array element, so have to remap 730 // destination and source variables to corresponding array 731 // elements. 732 CodeGenFunction::OMPPrivateScope Remap(*this); 733 Remap.addPrivate(DestVD, [DestElement]() { return DestElement; }); 734 Remap.addPrivate(SrcVD, [SrcElement]() { return SrcElement; }); 735 (void)Remap.Privatize(); 736 EmitIgnoredExpr(Copy); 737 }); 738 } 739 } else { 740 // Remap pseudo source variable to private copy. 741 CodeGenFunction::OMPPrivateScope Remap(*this); 742 Remap.addPrivate(SrcVD, [SrcAddr]() { return SrcAddr; }); 743 Remap.addPrivate(DestVD, [DestAddr]() { return DestAddr; }); 744 (void)Remap.Privatize(); 745 // Emit copying of the whole variable. 746 EmitIgnoredExpr(Copy); 747 } 748 } 749 750 bool CodeGenFunction::EmitOMPFirstprivateClause(const OMPExecutableDirective &D, 751 OMPPrivateScope &PrivateScope) { 752 if (!HaveInsertPoint()) 753 return false; 754 bool DeviceConstTarget = 755 getLangOpts().OpenMPIsDevice && 756 isOpenMPTargetExecutionDirective(D.getDirectiveKind()); 757 bool FirstprivateIsLastprivate = false; 758 llvm::DenseMap<const VarDecl *, OpenMPLastprivateModifier> Lastprivates; 759 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 760 for (const auto *D : C->varlists()) 761 Lastprivates.try_emplace( 762 cast<VarDecl>(cast<DeclRefExpr>(D)->getDecl())->getCanonicalDecl(), 763 C->getKind()); 764 } 765 llvm::DenseSet<const VarDecl *> EmittedAsFirstprivate; 766 llvm::SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 767 getOpenMPCaptureRegions(CaptureRegions, D.getDirectiveKind()); 768 // Force emission of the firstprivate copy if the directive does not emit 769 // outlined function, like omp for, omp simd, omp distribute etc. 770 bool MustEmitFirstprivateCopy = 771 CaptureRegions.size() == 1 && CaptureRegions.back() == OMPD_unknown; 772 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 773 const auto *IRef = C->varlist_begin(); 774 const auto *InitsRef = C->inits().begin(); 775 for (const Expr *IInit : C->private_copies()) { 776 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 777 bool ThisFirstprivateIsLastprivate = 778 Lastprivates.count(OrigVD->getCanonicalDecl()) > 0; 779 const FieldDecl *FD = CapturedStmtInfo->lookup(OrigVD); 780 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 781 if (!MustEmitFirstprivateCopy && !ThisFirstprivateIsLastprivate && FD && 782 !FD->getType()->isReferenceType() && 783 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 784 EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()); 785 ++IRef; 786 ++InitsRef; 787 continue; 788 } 789 // Do not emit copy for firstprivate constant variables in target regions, 790 // captured by reference. 791 if (DeviceConstTarget && OrigVD->getType().isConstant(getContext()) && 792 FD && FD->getType()->isReferenceType() && 793 (!VD || !VD->hasAttr<OMPAllocateDeclAttr>())) { 794 (void)CGM.getOpenMPRuntime().registerTargetFirstprivateCopy(*this, 795 OrigVD); 796 ++IRef; 797 ++InitsRef; 798 continue; 799 } 800 FirstprivateIsLastprivate = 801 FirstprivateIsLastprivate || ThisFirstprivateIsLastprivate; 802 if (EmittedAsFirstprivate.insert(OrigVD->getCanonicalDecl()).second) { 803 const auto *VDInit = 804 cast<VarDecl>(cast<DeclRefExpr>(*InitsRef)->getDecl()); 805 bool IsRegistered; 806 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 807 /*RefersToEnclosingVariableOrCapture=*/FD != nullptr, 808 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 809 LValue OriginalLVal; 810 if (!FD) { 811 // Check if the firstprivate variable is just a constant value. 812 ConstantEmission CE = tryEmitAsConstant(&DRE); 813 if (CE && !CE.isReference()) { 814 // Constant value, no need to create a copy. 815 ++IRef; 816 ++InitsRef; 817 continue; 818 } 819 if (CE && CE.isReference()) { 820 OriginalLVal = CE.getReferenceLValue(*this, &DRE); 821 } else { 822 assert(!CE && "Expected non-constant firstprivate."); 823 OriginalLVal = EmitLValue(&DRE); 824 } 825 } else { 826 OriginalLVal = EmitLValue(&DRE); 827 } 828 QualType Type = VD->getType(); 829 if (Type->isArrayType()) { 830 // Emit VarDecl with copy init for arrays. 831 // Get the address of the original variable captured in current 832 // captured region. 833 IsRegistered = PrivateScope.addPrivate( 834 OrigVD, [this, VD, Type, OriginalLVal, VDInit]() { 835 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 836 const Expr *Init = VD->getInit(); 837 if (!isa<CXXConstructExpr>(Init) || 838 isTrivialInitializer(Init)) { 839 // Perform simple memcpy. 840 LValue Dest = 841 MakeAddrLValue(Emission.getAllocatedAddress(), Type); 842 EmitAggregateAssign(Dest, OriginalLVal, Type); 843 } else { 844 EmitOMPAggregateAssign( 845 Emission.getAllocatedAddress(), 846 OriginalLVal.getAddress(*this), Type, 847 [this, VDInit, Init](Address DestElement, 848 Address SrcElement) { 849 // Clean up any temporaries needed by the 850 // initialization. 851 RunCleanupsScope InitScope(*this); 852 // Emit initialization for single element. 853 setAddrOfLocalVar(VDInit, SrcElement); 854 EmitAnyExprToMem(Init, DestElement, 855 Init->getType().getQualifiers(), 856 /*IsInitializer*/ false); 857 LocalDeclMap.erase(VDInit); 858 }); 859 } 860 EmitAutoVarCleanups(Emission); 861 return Emission.getAllocatedAddress(); 862 }); 863 } else { 864 Address OriginalAddr = OriginalLVal.getAddress(*this); 865 IsRegistered = 866 PrivateScope.addPrivate(OrigVD, [this, VDInit, OriginalAddr, VD, 867 ThisFirstprivateIsLastprivate, 868 OrigVD, &Lastprivates, IRef]() { 869 // Emit private VarDecl with copy init. 870 // Remap temp VDInit variable to the address of the original 871 // variable (for proper handling of captured global variables). 872 setAddrOfLocalVar(VDInit, OriginalAddr); 873 EmitDecl(*VD); 874 LocalDeclMap.erase(VDInit); 875 if (ThisFirstprivateIsLastprivate && 876 Lastprivates[OrigVD->getCanonicalDecl()] == 877 OMPC_LASTPRIVATE_conditional) { 878 // Create/init special variable for lastprivate conditionals. 879 Address VDAddr = 880 CGM.getOpenMPRuntime().emitLastprivateConditionalInit( 881 *this, OrigVD); 882 llvm::Value *V = EmitLoadOfScalar( 883 MakeAddrLValue(GetAddrOfLocalVar(VD), (*IRef)->getType(), 884 AlignmentSource::Decl), 885 (*IRef)->getExprLoc()); 886 EmitStoreOfScalar(V, 887 MakeAddrLValue(VDAddr, (*IRef)->getType(), 888 AlignmentSource::Decl)); 889 LocalDeclMap.erase(VD); 890 setAddrOfLocalVar(VD, VDAddr); 891 return VDAddr; 892 } 893 return GetAddrOfLocalVar(VD); 894 }); 895 } 896 assert(IsRegistered && 897 "firstprivate var already registered as private"); 898 // Silence the warning about unused variable. 899 (void)IsRegistered; 900 } 901 ++IRef; 902 ++InitsRef; 903 } 904 } 905 return FirstprivateIsLastprivate && !EmittedAsFirstprivate.empty(); 906 } 907 908 void CodeGenFunction::EmitOMPPrivateClause( 909 const OMPExecutableDirective &D, 910 CodeGenFunction::OMPPrivateScope &PrivateScope) { 911 if (!HaveInsertPoint()) 912 return; 913 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 914 for (const auto *C : D.getClausesOfKind<OMPPrivateClause>()) { 915 auto IRef = C->varlist_begin(); 916 for (const Expr *IInit : C->private_copies()) { 917 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 918 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 919 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 920 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD]() { 921 // Emit private VarDecl with copy init. 922 EmitDecl(*VD); 923 return GetAddrOfLocalVar(VD); 924 }); 925 assert(IsRegistered && "private var already registered as private"); 926 // Silence the warning about unused variable. 927 (void)IsRegistered; 928 } 929 ++IRef; 930 } 931 } 932 } 933 934 bool CodeGenFunction::EmitOMPCopyinClause(const OMPExecutableDirective &D) { 935 if (!HaveInsertPoint()) 936 return false; 937 // threadprivate_var1 = master_threadprivate_var1; 938 // operator=(threadprivate_var2, master_threadprivate_var2); 939 // ... 940 // __kmpc_barrier(&loc, global_tid); 941 llvm::DenseSet<const VarDecl *> CopiedVars; 942 llvm::BasicBlock *CopyBegin = nullptr, *CopyEnd = nullptr; 943 for (const auto *C : D.getClausesOfKind<OMPCopyinClause>()) { 944 auto IRef = C->varlist_begin(); 945 auto ISrcRef = C->source_exprs().begin(); 946 auto IDestRef = C->destination_exprs().begin(); 947 for (const Expr *AssignOp : C->assignment_ops()) { 948 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 949 QualType Type = VD->getType(); 950 if (CopiedVars.insert(VD->getCanonicalDecl()).second) { 951 // Get the address of the master variable. If we are emitting code with 952 // TLS support, the address is passed from the master as field in the 953 // captured declaration. 954 Address MasterAddr = Address::invalid(); 955 if (getLangOpts().OpenMPUseTLS && 956 getContext().getTargetInfo().isTLSSupported()) { 957 assert(CapturedStmtInfo->lookup(VD) && 958 "Copyin threadprivates should have been captured!"); 959 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), true, 960 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 961 MasterAddr = EmitLValue(&DRE).getAddress(*this); 962 LocalDeclMap.erase(VD); 963 } else { 964 MasterAddr = 965 Address(VD->isStaticLocal() ? CGM.getStaticLocalDeclAddress(VD) 966 : CGM.GetAddrOfGlobal(VD), 967 getContext().getDeclAlign(VD)); 968 } 969 // Get the address of the threadprivate variable. 970 Address PrivateAddr = EmitLValue(*IRef).getAddress(*this); 971 if (CopiedVars.size() == 1) { 972 // At first check if current thread is a master thread. If it is, no 973 // need to copy data. 974 CopyBegin = createBasicBlock("copyin.not.master"); 975 CopyEnd = createBasicBlock("copyin.not.master.end"); 976 Builder.CreateCondBr( 977 Builder.CreateICmpNE( 978 Builder.CreatePtrToInt(MasterAddr.getPointer(), CGM.IntPtrTy), 979 Builder.CreatePtrToInt(PrivateAddr.getPointer(), 980 CGM.IntPtrTy)), 981 CopyBegin, CopyEnd); 982 EmitBlock(CopyBegin); 983 } 984 const auto *SrcVD = 985 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 986 const auto *DestVD = 987 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 988 EmitOMPCopy(Type, PrivateAddr, MasterAddr, DestVD, SrcVD, AssignOp); 989 } 990 ++IRef; 991 ++ISrcRef; 992 ++IDestRef; 993 } 994 } 995 if (CopyEnd) { 996 // Exit out of copying procedure for non-master thread. 997 EmitBlock(CopyEnd, /*IsFinished=*/true); 998 return true; 999 } 1000 return false; 1001 } 1002 1003 bool CodeGenFunction::EmitOMPLastprivateClauseInit( 1004 const OMPExecutableDirective &D, OMPPrivateScope &PrivateScope) { 1005 if (!HaveInsertPoint()) 1006 return false; 1007 bool HasAtLeastOneLastprivate = false; 1008 llvm::DenseSet<const VarDecl *> SIMDLCVs; 1009 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 1010 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 1011 for (const Expr *C : LoopDirective->counters()) { 1012 SIMDLCVs.insert( 1013 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 1014 } 1015 } 1016 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1017 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1018 HasAtLeastOneLastprivate = true; 1019 if (isOpenMPTaskLoopDirective(D.getDirectiveKind()) && 1020 !getLangOpts().OpenMPSimd) 1021 break; 1022 const auto *IRef = C->varlist_begin(); 1023 const auto *IDestRef = C->destination_exprs().begin(); 1024 for (const Expr *IInit : C->private_copies()) { 1025 // Keep the address of the original variable for future update at the end 1026 // of the loop. 1027 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1028 // Taskloops do not require additional initialization, it is done in 1029 // runtime support library. 1030 if (AlreadyEmittedVars.insert(OrigVD->getCanonicalDecl()).second) { 1031 const auto *DestVD = 1032 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1033 PrivateScope.addPrivate(DestVD, [this, OrigVD, IRef]() { 1034 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1035 /*RefersToEnclosingVariableOrCapture=*/ 1036 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1037 (*IRef)->getType(), VK_LValue, (*IRef)->getExprLoc()); 1038 return EmitLValue(&DRE).getAddress(*this); 1039 }); 1040 // Check if the variable is also a firstprivate: in this case IInit is 1041 // not generated. Initialization of this variable will happen in codegen 1042 // for 'firstprivate' clause. 1043 if (IInit && !SIMDLCVs.count(OrigVD->getCanonicalDecl())) { 1044 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IInit)->getDecl()); 1045 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, VD, C, 1046 OrigVD]() { 1047 if (C->getKind() == OMPC_LASTPRIVATE_conditional) { 1048 Address VDAddr = 1049 CGM.getOpenMPRuntime().emitLastprivateConditionalInit(*this, 1050 OrigVD); 1051 setAddrOfLocalVar(VD, VDAddr); 1052 return VDAddr; 1053 } 1054 // Emit private VarDecl with copy init. 1055 EmitDecl(*VD); 1056 return GetAddrOfLocalVar(VD); 1057 }); 1058 assert(IsRegistered && 1059 "lastprivate var already registered as private"); 1060 (void)IsRegistered; 1061 } 1062 } 1063 ++IRef; 1064 ++IDestRef; 1065 } 1066 } 1067 return HasAtLeastOneLastprivate; 1068 } 1069 1070 void CodeGenFunction::EmitOMPLastprivateClauseFinal( 1071 const OMPExecutableDirective &D, bool NoFinals, 1072 llvm::Value *IsLastIterCond) { 1073 if (!HaveInsertPoint()) 1074 return; 1075 // Emit following code: 1076 // if (<IsLastIterCond>) { 1077 // orig_var1 = private_orig_var1; 1078 // ... 1079 // orig_varn = private_orig_varn; 1080 // } 1081 llvm::BasicBlock *ThenBB = nullptr; 1082 llvm::BasicBlock *DoneBB = nullptr; 1083 if (IsLastIterCond) { 1084 // Emit implicit barrier if at least one lastprivate conditional is found 1085 // and this is not a simd mode. 1086 if (!getLangOpts().OpenMPSimd && 1087 llvm::any_of(D.getClausesOfKind<OMPLastprivateClause>(), 1088 [](const OMPLastprivateClause *C) { 1089 return C->getKind() == OMPC_LASTPRIVATE_conditional; 1090 })) { 1091 CGM.getOpenMPRuntime().emitBarrierCall(*this, D.getBeginLoc(), 1092 OMPD_unknown, 1093 /*EmitChecks=*/false, 1094 /*ForceSimpleCall=*/true); 1095 } 1096 ThenBB = createBasicBlock(".omp.lastprivate.then"); 1097 DoneBB = createBasicBlock(".omp.lastprivate.done"); 1098 Builder.CreateCondBr(IsLastIterCond, ThenBB, DoneBB); 1099 EmitBlock(ThenBB); 1100 } 1101 llvm::DenseSet<const VarDecl *> AlreadyEmittedVars; 1102 llvm::DenseMap<const VarDecl *, const Expr *> LoopCountersAndUpdates; 1103 if (const auto *LoopDirective = dyn_cast<OMPLoopDirective>(&D)) { 1104 auto IC = LoopDirective->counters().begin(); 1105 for (const Expr *F : LoopDirective->finals()) { 1106 const auto *D = 1107 cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl())->getCanonicalDecl(); 1108 if (NoFinals) 1109 AlreadyEmittedVars.insert(D); 1110 else 1111 LoopCountersAndUpdates[D] = F; 1112 ++IC; 1113 } 1114 } 1115 for (const auto *C : D.getClausesOfKind<OMPLastprivateClause>()) { 1116 auto IRef = C->varlist_begin(); 1117 auto ISrcRef = C->source_exprs().begin(); 1118 auto IDestRef = C->destination_exprs().begin(); 1119 for (const Expr *AssignOp : C->assignment_ops()) { 1120 const auto *PrivateVD = 1121 cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 1122 QualType Type = PrivateVD->getType(); 1123 const auto *CanonicalVD = PrivateVD->getCanonicalDecl(); 1124 if (AlreadyEmittedVars.insert(CanonicalVD).second) { 1125 // If lastprivate variable is a loop control variable for loop-based 1126 // directive, update its value before copyin back to original 1127 // variable. 1128 if (const Expr *FinalExpr = LoopCountersAndUpdates.lookup(CanonicalVD)) 1129 EmitIgnoredExpr(FinalExpr); 1130 const auto *SrcVD = 1131 cast<VarDecl>(cast<DeclRefExpr>(*ISrcRef)->getDecl()); 1132 const auto *DestVD = 1133 cast<VarDecl>(cast<DeclRefExpr>(*IDestRef)->getDecl()); 1134 // Get the address of the private variable. 1135 Address PrivateAddr = GetAddrOfLocalVar(PrivateVD); 1136 if (const auto *RefTy = PrivateVD->getType()->getAs<ReferenceType>()) 1137 PrivateAddr = 1138 Address(Builder.CreateLoad(PrivateAddr), 1139 getNaturalTypeAlignment(RefTy->getPointeeType())); 1140 // Store the last value to the private copy in the last iteration. 1141 if (C->getKind() == OMPC_LASTPRIVATE_conditional) 1142 CGM.getOpenMPRuntime().emitLastprivateConditionalFinalUpdate( 1143 *this, MakeAddrLValue(PrivateAddr, (*IRef)->getType()), PrivateVD, 1144 (*IRef)->getExprLoc()); 1145 // Get the address of the original variable. 1146 Address OriginalAddr = GetAddrOfLocalVar(DestVD); 1147 EmitOMPCopy(Type, OriginalAddr, PrivateAddr, DestVD, SrcVD, AssignOp); 1148 } 1149 ++IRef; 1150 ++ISrcRef; 1151 ++IDestRef; 1152 } 1153 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 1154 EmitIgnoredExpr(PostUpdate); 1155 } 1156 if (IsLastIterCond) 1157 EmitBlock(DoneBB, /*IsFinished=*/true); 1158 } 1159 1160 void CodeGenFunction::EmitOMPReductionClauseInit( 1161 const OMPExecutableDirective &D, 1162 CodeGenFunction::OMPPrivateScope &PrivateScope) { 1163 if (!HaveInsertPoint()) 1164 return; 1165 SmallVector<const Expr *, 4> Shareds; 1166 SmallVector<const Expr *, 4> Privates; 1167 SmallVector<const Expr *, 4> ReductionOps; 1168 SmallVector<const Expr *, 4> LHSs; 1169 SmallVector<const Expr *, 4> RHSs; 1170 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1171 auto IPriv = C->privates().begin(); 1172 auto IRed = C->reduction_ops().begin(); 1173 auto ILHS = C->lhs_exprs().begin(); 1174 auto IRHS = C->rhs_exprs().begin(); 1175 for (const Expr *Ref : C->varlists()) { 1176 Shareds.emplace_back(Ref); 1177 Privates.emplace_back(*IPriv); 1178 ReductionOps.emplace_back(*IRed); 1179 LHSs.emplace_back(*ILHS); 1180 RHSs.emplace_back(*IRHS); 1181 std::advance(IPriv, 1); 1182 std::advance(IRed, 1); 1183 std::advance(ILHS, 1); 1184 std::advance(IRHS, 1); 1185 } 1186 } 1187 ReductionCodeGen RedCG(Shareds, Privates, ReductionOps); 1188 unsigned Count = 0; 1189 auto ILHS = LHSs.begin(); 1190 auto IRHS = RHSs.begin(); 1191 auto IPriv = Privates.begin(); 1192 for (const Expr *IRef : Shareds) { 1193 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*IPriv)->getDecl()); 1194 // Emit private VarDecl with reduction init. 1195 RedCG.emitSharedLValue(*this, Count); 1196 RedCG.emitAggregateType(*this, Count); 1197 AutoVarEmission Emission = EmitAutoVarAlloca(*PrivateVD); 1198 RedCG.emitInitialization(*this, Count, Emission.getAllocatedAddress(), 1199 RedCG.getSharedLValue(Count), 1200 [&Emission](CodeGenFunction &CGF) { 1201 CGF.EmitAutoVarInit(Emission); 1202 return true; 1203 }); 1204 EmitAutoVarCleanups(Emission); 1205 Address BaseAddr = RedCG.adjustPrivateAddress( 1206 *this, Count, Emission.getAllocatedAddress()); 1207 bool IsRegistered = PrivateScope.addPrivate( 1208 RedCG.getBaseDecl(Count), [BaseAddr]() { return BaseAddr; }); 1209 assert(IsRegistered && "private var already registered as private"); 1210 // Silence the warning about unused variable. 1211 (void)IsRegistered; 1212 1213 const auto *LHSVD = cast<VarDecl>(cast<DeclRefExpr>(*ILHS)->getDecl()); 1214 const auto *RHSVD = cast<VarDecl>(cast<DeclRefExpr>(*IRHS)->getDecl()); 1215 QualType Type = PrivateVD->getType(); 1216 bool isaOMPArraySectionExpr = isa<OMPArraySectionExpr>(IRef); 1217 if (isaOMPArraySectionExpr && Type->isVariablyModifiedType()) { 1218 // Store the address of the original variable associated with the LHS 1219 // implicit variable. 1220 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() { 1221 return RedCG.getSharedLValue(Count).getAddress(*this); 1222 }); 1223 PrivateScope.addPrivate( 1224 RHSVD, [this, PrivateVD]() { return GetAddrOfLocalVar(PrivateVD); }); 1225 } else if ((isaOMPArraySectionExpr && Type->isScalarType()) || 1226 isa<ArraySubscriptExpr>(IRef)) { 1227 // Store the address of the original variable associated with the LHS 1228 // implicit variable. 1229 PrivateScope.addPrivate(LHSVD, [&RedCG, Count, this]() { 1230 return RedCG.getSharedLValue(Count).getAddress(*this); 1231 }); 1232 PrivateScope.addPrivate(RHSVD, [this, PrivateVD, RHSVD]() { 1233 return Builder.CreateElementBitCast(GetAddrOfLocalVar(PrivateVD), 1234 ConvertTypeForMem(RHSVD->getType()), 1235 "rhs.begin"); 1236 }); 1237 } else { 1238 QualType Type = PrivateVD->getType(); 1239 bool IsArray = getContext().getAsArrayType(Type) != nullptr; 1240 Address OriginalAddr = RedCG.getSharedLValue(Count).getAddress(*this); 1241 // Store the address of the original variable associated with the LHS 1242 // implicit variable. 1243 if (IsArray) { 1244 OriginalAddr = Builder.CreateElementBitCast( 1245 OriginalAddr, ConvertTypeForMem(LHSVD->getType()), "lhs.begin"); 1246 } 1247 PrivateScope.addPrivate(LHSVD, [OriginalAddr]() { return OriginalAddr; }); 1248 PrivateScope.addPrivate( 1249 RHSVD, [this, PrivateVD, RHSVD, IsArray]() { 1250 return IsArray 1251 ? Builder.CreateElementBitCast( 1252 GetAddrOfLocalVar(PrivateVD), 1253 ConvertTypeForMem(RHSVD->getType()), "rhs.begin") 1254 : GetAddrOfLocalVar(PrivateVD); 1255 }); 1256 } 1257 ++ILHS; 1258 ++IRHS; 1259 ++IPriv; 1260 ++Count; 1261 } 1262 } 1263 1264 void CodeGenFunction::EmitOMPReductionClauseFinal( 1265 const OMPExecutableDirective &D, const OpenMPDirectiveKind ReductionKind) { 1266 if (!HaveInsertPoint()) 1267 return; 1268 llvm::SmallVector<const Expr *, 8> Privates; 1269 llvm::SmallVector<const Expr *, 8> LHSExprs; 1270 llvm::SmallVector<const Expr *, 8> RHSExprs; 1271 llvm::SmallVector<const Expr *, 8> ReductionOps; 1272 bool HasAtLeastOneReduction = false; 1273 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1274 HasAtLeastOneReduction = true; 1275 Privates.append(C->privates().begin(), C->privates().end()); 1276 LHSExprs.append(C->lhs_exprs().begin(), C->lhs_exprs().end()); 1277 RHSExprs.append(C->rhs_exprs().begin(), C->rhs_exprs().end()); 1278 ReductionOps.append(C->reduction_ops().begin(), C->reduction_ops().end()); 1279 } 1280 if (HasAtLeastOneReduction) { 1281 bool WithNowait = D.getSingleClause<OMPNowaitClause>() || 1282 isOpenMPParallelDirective(D.getDirectiveKind()) || 1283 ReductionKind == OMPD_simd; 1284 bool SimpleReduction = ReductionKind == OMPD_simd; 1285 // Emit nowait reduction if nowait clause is present or directive is a 1286 // parallel directive (it always has implicit barrier). 1287 CGM.getOpenMPRuntime().emitReduction( 1288 *this, D.getEndLoc(), Privates, LHSExprs, RHSExprs, ReductionOps, 1289 {WithNowait, SimpleReduction, ReductionKind}); 1290 } 1291 } 1292 1293 static void emitPostUpdateForReductionClause( 1294 CodeGenFunction &CGF, const OMPExecutableDirective &D, 1295 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1296 if (!CGF.HaveInsertPoint()) 1297 return; 1298 llvm::BasicBlock *DoneBB = nullptr; 1299 for (const auto *C : D.getClausesOfKind<OMPReductionClause>()) { 1300 if (const Expr *PostUpdate = C->getPostUpdateExpr()) { 1301 if (!DoneBB) { 1302 if (llvm::Value *Cond = CondGen(CGF)) { 1303 // If the first post-update expression is found, emit conditional 1304 // block if it was requested. 1305 llvm::BasicBlock *ThenBB = CGF.createBasicBlock(".omp.reduction.pu"); 1306 DoneBB = CGF.createBasicBlock(".omp.reduction.pu.done"); 1307 CGF.Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1308 CGF.EmitBlock(ThenBB); 1309 } 1310 } 1311 CGF.EmitIgnoredExpr(PostUpdate); 1312 } 1313 } 1314 if (DoneBB) 1315 CGF.EmitBlock(DoneBB, /*IsFinished=*/true); 1316 } 1317 1318 namespace { 1319 /// Codegen lambda for appending distribute lower and upper bounds to outlined 1320 /// parallel function. This is necessary for combined constructs such as 1321 /// 'distribute parallel for' 1322 typedef llvm::function_ref<void(CodeGenFunction &, 1323 const OMPExecutableDirective &, 1324 llvm::SmallVectorImpl<llvm::Value *> &)> 1325 CodeGenBoundParametersTy; 1326 } // anonymous namespace 1327 1328 static void 1329 checkForLastprivateConditionalUpdate(CodeGenFunction &CGF, 1330 const OMPExecutableDirective &S) { 1331 if (CGF.getLangOpts().OpenMP < 50) 1332 return; 1333 llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> PrivateDecls; 1334 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 1335 for (const Expr *Ref : C->varlists()) { 1336 if (!Ref->getType()->isScalarType()) 1337 continue; 1338 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1339 if (!DRE) 1340 continue; 1341 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1342 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1343 } 1344 } 1345 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 1346 for (const Expr *Ref : C->varlists()) { 1347 if (!Ref->getType()->isScalarType()) 1348 continue; 1349 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1350 if (!DRE) 1351 continue; 1352 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1353 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1354 } 1355 } 1356 for (const auto *C : S.getClausesOfKind<OMPLinearClause>()) { 1357 for (const Expr *Ref : C->varlists()) { 1358 if (!Ref->getType()->isScalarType()) 1359 continue; 1360 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1361 if (!DRE) 1362 continue; 1363 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1364 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, Ref); 1365 } 1366 } 1367 // Privates should ne analyzed since they are not captured at all. 1368 // Task reductions may be skipped - tasks are ignored. 1369 // Firstprivates do not return value but may be passed by reference - no need 1370 // to check for updated lastprivate conditional. 1371 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 1372 for (const Expr *Ref : C->varlists()) { 1373 if (!Ref->getType()->isScalarType()) 1374 continue; 1375 const auto *DRE = dyn_cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 1376 if (!DRE) 1377 continue; 1378 PrivateDecls.insert(cast<VarDecl>(DRE->getDecl())); 1379 } 1380 } 1381 CGF.CGM.getOpenMPRuntime().checkAndEmitSharedLastprivateConditional( 1382 CGF, S, PrivateDecls); 1383 } 1384 1385 static void emitCommonOMPParallelDirective( 1386 CodeGenFunction &CGF, const OMPExecutableDirective &S, 1387 OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, 1388 const CodeGenBoundParametersTy &CodeGenBoundParameters) { 1389 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1390 llvm::Function *OutlinedFn = 1391 CGF.CGM.getOpenMPRuntime().emitParallelOutlinedFunction( 1392 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 1393 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) { 1394 CodeGenFunction::RunCleanupsScope NumThreadsScope(CGF); 1395 llvm::Value *NumThreads = 1396 CGF.EmitScalarExpr(NumThreadsClause->getNumThreads(), 1397 /*IgnoreResultAssign=*/true); 1398 CGF.CGM.getOpenMPRuntime().emitNumThreadsClause( 1399 CGF, NumThreads, NumThreadsClause->getBeginLoc()); 1400 } 1401 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) { 1402 CodeGenFunction::RunCleanupsScope ProcBindScope(CGF); 1403 CGF.CGM.getOpenMPRuntime().emitProcBindClause( 1404 CGF, ProcBindClause->getProcBindKind(), ProcBindClause->getBeginLoc()); 1405 } 1406 const Expr *IfCond = nullptr; 1407 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 1408 if (C->getNameModifier() == OMPD_unknown || 1409 C->getNameModifier() == OMPD_parallel) { 1410 IfCond = C->getCondition(); 1411 break; 1412 } 1413 } 1414 1415 OMPParallelScope Scope(CGF, S); 1416 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 1417 // Combining 'distribute' with 'for' requires sharing each 'distribute' chunk 1418 // lower and upper bounds with the pragma 'for' chunking mechanism. 1419 // The following lambda takes care of appending the lower and upper bound 1420 // parameters when necessary 1421 CodeGenBoundParameters(CGF, S, CapturedVars); 1422 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 1423 CGF.CGM.getOpenMPRuntime().emitParallelCall(CGF, S.getBeginLoc(), OutlinedFn, 1424 CapturedVars, IfCond); 1425 } 1426 1427 static void emitEmptyBoundParameters(CodeGenFunction &, 1428 const OMPExecutableDirective &, 1429 llvm::SmallVectorImpl<llvm::Value *> &) {} 1430 1431 void CodeGenFunction::EmitOMPParallelDirective(const OMPParallelDirective &S) { 1432 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 1433 // Check if we have any if clause associated with the directive. 1434 llvm::Value *IfCond = nullptr; 1435 if (const auto *C = S.getSingleClause<OMPIfClause>()) 1436 IfCond = EmitScalarExpr(C->getCondition(), 1437 /*IgnoreResultAssign=*/true); 1438 1439 llvm::Value *NumThreads = nullptr; 1440 if (const auto *NumThreadsClause = S.getSingleClause<OMPNumThreadsClause>()) 1441 NumThreads = EmitScalarExpr(NumThreadsClause->getNumThreads(), 1442 /*IgnoreResultAssign=*/true); 1443 1444 ProcBindKind ProcBind = OMP_PROC_BIND_default; 1445 if (const auto *ProcBindClause = S.getSingleClause<OMPProcBindClause>()) 1446 ProcBind = ProcBindClause->getProcBindKind(); 1447 1448 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 1449 1450 // The cleanup callback that finalizes all variabels at the given location, 1451 // thus calls destructors etc. 1452 auto FiniCB = [this](InsertPointTy IP) { 1453 CGBuilderTy::InsertPointGuard IPG(Builder); 1454 assert(IP.getBlock()->end() != IP.getPoint() && 1455 "OpenMP IR Builder should cause terminated block!"); 1456 llvm::BasicBlock *IPBB = IP.getBlock(); 1457 llvm::BasicBlock *DestBB = IPBB->splitBasicBlock(IP.getPoint()); 1458 IPBB->getTerminator()->eraseFromParent(); 1459 Builder.SetInsertPoint(IPBB); 1460 CodeGenFunction::JumpDest Dest = getJumpDestInCurrentScope(DestBB); 1461 EmitBranchThroughCleanup(Dest); 1462 }; 1463 1464 // Privatization callback that performs appropriate action for 1465 // shared/private/firstprivate/lastprivate/copyin/... variables. 1466 // 1467 // TODO: This defaults to shared right now. 1468 auto PrivCB = [](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1469 llvm::Value &Val, llvm::Value *&ReplVal) { 1470 // The next line is appropriate only for variables (Val) with the 1471 // data-sharing attribute "shared". 1472 ReplVal = &Val; 1473 1474 return CodeGenIP; 1475 }; 1476 1477 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 1478 const Stmt *ParallelRegionBodyStmt = CS->getCapturedStmt(); 1479 1480 auto BodyGenCB = [ParallelRegionBodyStmt, 1481 this](InsertPointTy AllocaIP, InsertPointTy CodeGenIP, 1482 llvm::BasicBlock &ContinuationBB) { 1483 auto OldAllocaIP = AllocaInsertPt; 1484 AllocaInsertPt = &*AllocaIP.getPoint(); 1485 1486 auto OldReturnBlock = ReturnBlock; 1487 ReturnBlock = getJumpDestInCurrentScope(&ContinuationBB); 1488 1489 llvm::BasicBlock *CodeGenIPBB = CodeGenIP.getBlock(); 1490 CodeGenIPBB->splitBasicBlock(CodeGenIP.getPoint()); 1491 llvm::Instruction *CodeGenIPBBTI = CodeGenIPBB->getTerminator(); 1492 CodeGenIPBBTI->removeFromParent(); 1493 1494 Builder.SetInsertPoint(CodeGenIPBB); 1495 1496 EmitStmt(ParallelRegionBodyStmt); 1497 1498 Builder.Insert(CodeGenIPBBTI); 1499 1500 AllocaInsertPt = OldAllocaIP; 1501 ReturnBlock = OldReturnBlock; 1502 }; 1503 1504 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 1505 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 1506 Builder.restoreIP(OMPBuilder->CreateParallel(Builder, BodyGenCB, PrivCB, 1507 FiniCB, IfCond, NumThreads, 1508 ProcBind, S.hasCancel())); 1509 return; 1510 } 1511 1512 // Emit parallel region as a standalone region. 1513 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 1514 Action.Enter(CGF); 1515 OMPPrivateScope PrivateScope(CGF); 1516 bool Copyins = CGF.EmitOMPCopyinClause(S); 1517 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 1518 if (Copyins) { 1519 // Emit implicit barrier to synchronize threads and avoid data races on 1520 // propagation master's thread values of threadprivate variables to local 1521 // instances of that variables of all other implicit threads. 1522 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 1523 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 1524 /*ForceSimpleCall=*/true); 1525 } 1526 CGF.EmitOMPPrivateClause(S, PrivateScope); 1527 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 1528 (void)PrivateScope.Privatize(); 1529 CGF.EmitStmt(S.getCapturedStmt(OMPD_parallel)->getCapturedStmt()); 1530 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 1531 }; 1532 { 1533 auto LPCRegion = 1534 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 1535 emitCommonOMPParallelDirective(*this, S, OMPD_parallel, CodeGen, 1536 emitEmptyBoundParameters); 1537 emitPostUpdateForReductionClause(*this, S, 1538 [](CodeGenFunction &) { return nullptr; }); 1539 } 1540 // Check for outer lastprivate conditional update. 1541 checkForLastprivateConditionalUpdate(*this, S); 1542 } 1543 1544 static void emitBody(CodeGenFunction &CGF, const Stmt *S, const Stmt *NextLoop, 1545 int MaxLevel, int Level = 0) { 1546 assert(Level < MaxLevel && "Too deep lookup during loop body codegen."); 1547 const Stmt *SimplifiedS = S->IgnoreContainers(); 1548 if (const auto *CS = dyn_cast<CompoundStmt>(SimplifiedS)) { 1549 PrettyStackTraceLoc CrashInfo( 1550 CGF.getContext().getSourceManager(), CS->getLBracLoc(), 1551 "LLVM IR generation of compound statement ('{}')"); 1552 1553 // Keep track of the current cleanup stack depth, including debug scopes. 1554 CodeGenFunction::LexicalScope Scope(CGF, S->getSourceRange()); 1555 for (const Stmt *CurStmt : CS->body()) 1556 emitBody(CGF, CurStmt, NextLoop, MaxLevel, Level); 1557 return; 1558 } 1559 if (SimplifiedS == NextLoop) { 1560 if (const auto *For = dyn_cast<ForStmt>(SimplifiedS)) { 1561 S = For->getBody(); 1562 } else { 1563 assert(isa<CXXForRangeStmt>(SimplifiedS) && 1564 "Expected canonical for loop or range-based for loop."); 1565 const auto *CXXFor = cast<CXXForRangeStmt>(SimplifiedS); 1566 CGF.EmitStmt(CXXFor->getLoopVarStmt()); 1567 S = CXXFor->getBody(); 1568 } 1569 if (Level + 1 < MaxLevel) { 1570 NextLoop = OMPLoopDirective::tryToFindNextInnerLoop( 1571 S, /*TryImperfectlyNestedLoops=*/true); 1572 emitBody(CGF, S, NextLoop, MaxLevel, Level + 1); 1573 return; 1574 } 1575 } 1576 CGF.EmitStmt(S); 1577 } 1578 1579 void CodeGenFunction::EmitOMPLoopBody(const OMPLoopDirective &D, 1580 JumpDest LoopExit) { 1581 RunCleanupsScope BodyScope(*this); 1582 // Update counters values on current iteration. 1583 for (const Expr *UE : D.updates()) 1584 EmitIgnoredExpr(UE); 1585 // Update the linear variables. 1586 // In distribute directives only loop counters may be marked as linear, no 1587 // need to generate the code for them. 1588 if (!isOpenMPDistributeDirective(D.getDirectiveKind())) { 1589 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1590 for (const Expr *UE : C->updates()) 1591 EmitIgnoredExpr(UE); 1592 } 1593 } 1594 1595 // On a continue in the body, jump to the end. 1596 JumpDest Continue = getJumpDestInCurrentScope("omp.body.continue"); 1597 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1598 for (const Expr *E : D.finals_conditions()) { 1599 if (!E) 1600 continue; 1601 // Check that loop counter in non-rectangular nest fits into the iteration 1602 // space. 1603 llvm::BasicBlock *NextBB = createBasicBlock("omp.body.next"); 1604 EmitBranchOnBoolExpr(E, NextBB, Continue.getBlock(), 1605 getProfileCount(D.getBody())); 1606 EmitBlock(NextBB); 1607 } 1608 // Emit loop variables for C++ range loops. 1609 const Stmt *Body = 1610 D.getInnermostCapturedStmt()->getCapturedStmt()->IgnoreContainers(); 1611 // Emit loop body. 1612 emitBody(*this, Body, 1613 OMPLoopDirective::tryToFindNextInnerLoop( 1614 Body, /*TryImperfectlyNestedLoops=*/true), 1615 D.getCollapsedNumber()); 1616 1617 // The end (updates/cleanups). 1618 EmitBlock(Continue.getBlock()); 1619 BreakContinueStack.pop_back(); 1620 } 1621 1622 void CodeGenFunction::EmitOMPInnerLoop( 1623 const Stmt &S, bool RequiresCleanup, const Expr *LoopCond, 1624 const Expr *IncExpr, 1625 const llvm::function_ref<void(CodeGenFunction &)> BodyGen, 1626 const llvm::function_ref<void(CodeGenFunction &)> PostIncGen) { 1627 auto LoopExit = getJumpDestInCurrentScope("omp.inner.for.end"); 1628 1629 // Start the loop with a block that tests the condition. 1630 auto CondBlock = createBasicBlock("omp.inner.for.cond"); 1631 EmitBlock(CondBlock); 1632 const SourceRange R = S.getSourceRange(); 1633 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 1634 SourceLocToDebugLoc(R.getEnd())); 1635 1636 // If there are any cleanups between here and the loop-exit scope, 1637 // create a block to stage a loop exit along. 1638 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 1639 if (RequiresCleanup) 1640 ExitBlock = createBasicBlock("omp.inner.for.cond.cleanup"); 1641 1642 llvm::BasicBlock *LoopBody = createBasicBlock("omp.inner.for.body"); 1643 1644 // Emit condition. 1645 EmitBranchOnBoolExpr(LoopCond, LoopBody, ExitBlock, getProfileCount(&S)); 1646 if (ExitBlock != LoopExit.getBlock()) { 1647 EmitBlock(ExitBlock); 1648 EmitBranchThroughCleanup(LoopExit); 1649 } 1650 1651 EmitBlock(LoopBody); 1652 incrementProfileCounter(&S); 1653 1654 // Create a block for the increment. 1655 JumpDest Continue = getJumpDestInCurrentScope("omp.inner.for.inc"); 1656 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 1657 1658 BodyGen(*this); 1659 1660 // Emit "IV = IV + 1" and a back-edge to the condition block. 1661 EmitBlock(Continue.getBlock()); 1662 EmitIgnoredExpr(IncExpr); 1663 PostIncGen(*this); 1664 BreakContinueStack.pop_back(); 1665 EmitBranch(CondBlock); 1666 LoopStack.pop(); 1667 // Emit the fall-through block. 1668 EmitBlock(LoopExit.getBlock()); 1669 } 1670 1671 bool CodeGenFunction::EmitOMPLinearClauseInit(const OMPLoopDirective &D) { 1672 if (!HaveInsertPoint()) 1673 return false; 1674 // Emit inits for the linear variables. 1675 bool HasLinears = false; 1676 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1677 for (const Expr *Init : C->inits()) { 1678 HasLinears = true; 1679 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(Init)->getDecl()); 1680 if (const auto *Ref = 1681 dyn_cast<DeclRefExpr>(VD->getInit()->IgnoreImpCasts())) { 1682 AutoVarEmission Emission = EmitAutoVarAlloca(*VD); 1683 const auto *OrigVD = cast<VarDecl>(Ref->getDecl()); 1684 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1685 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1686 VD->getInit()->getType(), VK_LValue, 1687 VD->getInit()->getExprLoc()); 1688 EmitExprAsInit(&DRE, VD, MakeAddrLValue(Emission.getAllocatedAddress(), 1689 VD->getType()), 1690 /*capturedByInit=*/false); 1691 EmitAutoVarCleanups(Emission); 1692 } else { 1693 EmitVarDecl(*VD); 1694 } 1695 } 1696 // Emit the linear steps for the linear clauses. 1697 // If a step is not constant, it is pre-calculated before the loop. 1698 if (const auto *CS = cast_or_null<BinaryOperator>(C->getCalcStep())) 1699 if (const auto *SaveRef = cast<DeclRefExpr>(CS->getLHS())) { 1700 EmitVarDecl(*cast<VarDecl>(SaveRef->getDecl())); 1701 // Emit calculation of the linear step. 1702 EmitIgnoredExpr(CS); 1703 } 1704 } 1705 return HasLinears; 1706 } 1707 1708 void CodeGenFunction::EmitOMPLinearClauseFinal( 1709 const OMPLoopDirective &D, 1710 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1711 if (!HaveInsertPoint()) 1712 return; 1713 llvm::BasicBlock *DoneBB = nullptr; 1714 // Emit the final values of the linear variables. 1715 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1716 auto IC = C->varlist_begin(); 1717 for (const Expr *F : C->finals()) { 1718 if (!DoneBB) { 1719 if (llvm::Value *Cond = CondGen(*this)) { 1720 // If the first post-update expression is found, emit conditional 1721 // block if it was requested. 1722 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.linear.pu"); 1723 DoneBB = createBasicBlock(".omp.linear.pu.done"); 1724 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1725 EmitBlock(ThenBB); 1726 } 1727 } 1728 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IC)->getDecl()); 1729 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(OrigVD), 1730 CapturedStmtInfo->lookup(OrigVD) != nullptr, 1731 (*IC)->getType(), VK_LValue, (*IC)->getExprLoc()); 1732 Address OrigAddr = EmitLValue(&DRE).getAddress(*this); 1733 CodeGenFunction::OMPPrivateScope VarScope(*this); 1734 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 1735 (void)VarScope.Privatize(); 1736 EmitIgnoredExpr(F); 1737 ++IC; 1738 } 1739 if (const Expr *PostUpdate = C->getPostUpdateExpr()) 1740 EmitIgnoredExpr(PostUpdate); 1741 } 1742 if (DoneBB) 1743 EmitBlock(DoneBB, /*IsFinished=*/true); 1744 } 1745 1746 static void emitAlignedClause(CodeGenFunction &CGF, 1747 const OMPExecutableDirective &D) { 1748 if (!CGF.HaveInsertPoint()) 1749 return; 1750 for (const auto *Clause : D.getClausesOfKind<OMPAlignedClause>()) { 1751 llvm::APInt ClauseAlignment(64, 0); 1752 if (const Expr *AlignmentExpr = Clause->getAlignment()) { 1753 auto *AlignmentCI = 1754 cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AlignmentExpr)); 1755 ClauseAlignment = AlignmentCI->getValue(); 1756 } 1757 for (const Expr *E : Clause->varlists()) { 1758 llvm::APInt Alignment(ClauseAlignment); 1759 if (Alignment == 0) { 1760 // OpenMP [2.8.1, Description] 1761 // If no optional parameter is specified, implementation-defined default 1762 // alignments for SIMD instructions on the target platforms are assumed. 1763 Alignment = 1764 CGF.getContext() 1765 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign( 1766 E->getType()->getPointeeType())) 1767 .getQuantity(); 1768 } 1769 assert((Alignment == 0 || Alignment.isPowerOf2()) && 1770 "alignment is not power of 2"); 1771 if (Alignment != 0) { 1772 llvm::Value *PtrValue = CGF.EmitScalarExpr(E); 1773 CGF.emitAlignmentAssumption( 1774 PtrValue, E, /*No second loc needed*/ SourceLocation(), 1775 llvm::ConstantInt::get(CGF.getLLVMContext(), Alignment)); 1776 } 1777 } 1778 } 1779 } 1780 1781 void CodeGenFunction::EmitOMPPrivateLoopCounters( 1782 const OMPLoopDirective &S, CodeGenFunction::OMPPrivateScope &LoopScope) { 1783 if (!HaveInsertPoint()) 1784 return; 1785 auto I = S.private_counters().begin(); 1786 for (const Expr *E : S.counters()) { 1787 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1788 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()); 1789 // Emit var without initialization. 1790 AutoVarEmission VarEmission = EmitAutoVarAlloca(*PrivateVD); 1791 EmitAutoVarCleanups(VarEmission); 1792 LocalDeclMap.erase(PrivateVD); 1793 (void)LoopScope.addPrivate(VD, [&VarEmission]() { 1794 return VarEmission.getAllocatedAddress(); 1795 }); 1796 if (LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD) || 1797 VD->hasGlobalStorage()) { 1798 (void)LoopScope.addPrivate(PrivateVD, [this, VD, E]() { 1799 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(VD), 1800 LocalDeclMap.count(VD) || CapturedStmtInfo->lookup(VD), 1801 E->getType(), VK_LValue, E->getExprLoc()); 1802 return EmitLValue(&DRE).getAddress(*this); 1803 }); 1804 } else { 1805 (void)LoopScope.addPrivate(PrivateVD, [&VarEmission]() { 1806 return VarEmission.getAllocatedAddress(); 1807 }); 1808 } 1809 ++I; 1810 } 1811 // Privatize extra loop counters used in loops for ordered(n) clauses. 1812 for (const auto *C : S.getClausesOfKind<OMPOrderedClause>()) { 1813 if (!C->getNumForLoops()) 1814 continue; 1815 for (unsigned I = S.getCollapsedNumber(), 1816 E = C->getLoopNumIterations().size(); 1817 I < E; ++I) { 1818 const auto *DRE = cast<DeclRefExpr>(C->getLoopCounter(I)); 1819 const auto *VD = cast<VarDecl>(DRE->getDecl()); 1820 // Override only those variables that can be captured to avoid re-emission 1821 // of the variables declared within the loops. 1822 if (DRE->refersToEnclosingVariableOrCapture()) { 1823 (void)LoopScope.addPrivate(VD, [this, DRE, VD]() { 1824 return CreateMemTemp(DRE->getType(), VD->getName()); 1825 }); 1826 } 1827 } 1828 } 1829 } 1830 1831 static void emitPreCond(CodeGenFunction &CGF, const OMPLoopDirective &S, 1832 const Expr *Cond, llvm::BasicBlock *TrueBlock, 1833 llvm::BasicBlock *FalseBlock, uint64_t TrueCount) { 1834 if (!CGF.HaveInsertPoint()) 1835 return; 1836 { 1837 CodeGenFunction::OMPPrivateScope PreCondScope(CGF); 1838 CGF.EmitOMPPrivateLoopCounters(S, PreCondScope); 1839 (void)PreCondScope.Privatize(); 1840 // Get initial values of real counters. 1841 for (const Expr *I : S.inits()) { 1842 CGF.EmitIgnoredExpr(I); 1843 } 1844 } 1845 // Create temp loop control variables with their init values to support 1846 // non-rectangular loops. 1847 CodeGenFunction::OMPMapVars PreCondVars; 1848 for (const Expr * E: S.dependent_counters()) { 1849 if (!E) 1850 continue; 1851 assert(!E->getType().getNonReferenceType()->isRecordType() && 1852 "dependent counter must not be an iterator."); 1853 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1854 Address CounterAddr = 1855 CGF.CreateMemTemp(VD->getType().getNonReferenceType()); 1856 (void)PreCondVars.setVarAddr(CGF, VD, CounterAddr); 1857 } 1858 (void)PreCondVars.apply(CGF); 1859 for (const Expr *E : S.dependent_inits()) { 1860 if (!E) 1861 continue; 1862 CGF.EmitIgnoredExpr(E); 1863 } 1864 // Check that loop is executed at least one time. 1865 CGF.EmitBranchOnBoolExpr(Cond, TrueBlock, FalseBlock, TrueCount); 1866 PreCondVars.restore(CGF); 1867 } 1868 1869 void CodeGenFunction::EmitOMPLinearClause( 1870 const OMPLoopDirective &D, CodeGenFunction::OMPPrivateScope &PrivateScope) { 1871 if (!HaveInsertPoint()) 1872 return; 1873 llvm::DenseSet<const VarDecl *> SIMDLCVs; 1874 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 1875 const auto *LoopDirective = cast<OMPLoopDirective>(&D); 1876 for (const Expr *C : LoopDirective->counters()) { 1877 SIMDLCVs.insert( 1878 cast<VarDecl>(cast<DeclRefExpr>(C)->getDecl())->getCanonicalDecl()); 1879 } 1880 } 1881 for (const auto *C : D.getClausesOfKind<OMPLinearClause>()) { 1882 auto CurPrivate = C->privates().begin(); 1883 for (const Expr *E : C->varlists()) { 1884 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 1885 const auto *PrivateVD = 1886 cast<VarDecl>(cast<DeclRefExpr>(*CurPrivate)->getDecl()); 1887 if (!SIMDLCVs.count(VD->getCanonicalDecl())) { 1888 bool IsRegistered = PrivateScope.addPrivate(VD, [this, PrivateVD]() { 1889 // Emit private VarDecl with copy init. 1890 EmitVarDecl(*PrivateVD); 1891 return GetAddrOfLocalVar(PrivateVD); 1892 }); 1893 assert(IsRegistered && "linear var already registered as private"); 1894 // Silence the warning about unused variable. 1895 (void)IsRegistered; 1896 } else { 1897 EmitVarDecl(*PrivateVD); 1898 } 1899 ++CurPrivate; 1900 } 1901 } 1902 } 1903 1904 static void emitSimdlenSafelenClause(CodeGenFunction &CGF, 1905 const OMPExecutableDirective &D, 1906 bool IsMonotonic) { 1907 if (!CGF.HaveInsertPoint()) 1908 return; 1909 if (const auto *C = D.getSingleClause<OMPSimdlenClause>()) { 1910 RValue Len = CGF.EmitAnyExpr(C->getSimdlen(), AggValueSlot::ignored(), 1911 /*ignoreResult=*/true); 1912 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 1913 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 1914 // In presence of finite 'safelen', it may be unsafe to mark all 1915 // the memory instructions parallel, because loop-carried 1916 // dependences of 'safelen' iterations are possible. 1917 if (!IsMonotonic) 1918 CGF.LoopStack.setParallel(!D.getSingleClause<OMPSafelenClause>()); 1919 } else if (const auto *C = D.getSingleClause<OMPSafelenClause>()) { 1920 RValue Len = CGF.EmitAnyExpr(C->getSafelen(), AggValueSlot::ignored(), 1921 /*ignoreResult=*/true); 1922 auto *Val = cast<llvm::ConstantInt>(Len.getScalarVal()); 1923 CGF.LoopStack.setVectorizeWidth(Val->getZExtValue()); 1924 // In presence of finite 'safelen', it may be unsafe to mark all 1925 // the memory instructions parallel, because loop-carried 1926 // dependences of 'safelen' iterations are possible. 1927 CGF.LoopStack.setParallel(/*Enable=*/false); 1928 } 1929 } 1930 1931 void CodeGenFunction::EmitOMPSimdInit(const OMPLoopDirective &D, 1932 bool IsMonotonic) { 1933 // Walk clauses and process safelen/lastprivate. 1934 LoopStack.setParallel(!IsMonotonic); 1935 LoopStack.setVectorizeEnable(); 1936 emitSimdlenSafelenClause(*this, D, IsMonotonic); 1937 if (const auto *C = D.getSingleClause<OMPOrderClause>()) 1938 if (C->getKind() == OMPC_ORDER_concurrent) 1939 LoopStack.setParallel(/*Enable=*/true); 1940 } 1941 1942 void CodeGenFunction::EmitOMPSimdFinal( 1943 const OMPLoopDirective &D, 1944 const llvm::function_ref<llvm::Value *(CodeGenFunction &)> CondGen) { 1945 if (!HaveInsertPoint()) 1946 return; 1947 llvm::BasicBlock *DoneBB = nullptr; 1948 auto IC = D.counters().begin(); 1949 auto IPC = D.private_counters().begin(); 1950 for (const Expr *F : D.finals()) { 1951 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>((*IC))->getDecl()); 1952 const auto *PrivateVD = cast<VarDecl>(cast<DeclRefExpr>((*IPC))->getDecl()); 1953 const auto *CED = dyn_cast<OMPCapturedExprDecl>(OrigVD); 1954 if (LocalDeclMap.count(OrigVD) || CapturedStmtInfo->lookup(OrigVD) || 1955 OrigVD->hasGlobalStorage() || CED) { 1956 if (!DoneBB) { 1957 if (llvm::Value *Cond = CondGen(*this)) { 1958 // If the first post-update expression is found, emit conditional 1959 // block if it was requested. 1960 llvm::BasicBlock *ThenBB = createBasicBlock(".omp.final.then"); 1961 DoneBB = createBasicBlock(".omp.final.done"); 1962 Builder.CreateCondBr(Cond, ThenBB, DoneBB); 1963 EmitBlock(ThenBB); 1964 } 1965 } 1966 Address OrigAddr = Address::invalid(); 1967 if (CED) { 1968 OrigAddr = 1969 EmitLValue(CED->getInit()->IgnoreImpCasts()).getAddress(*this); 1970 } else { 1971 DeclRefExpr DRE(getContext(), const_cast<VarDecl *>(PrivateVD), 1972 /*RefersToEnclosingVariableOrCapture=*/false, 1973 (*IPC)->getType(), VK_LValue, (*IPC)->getExprLoc()); 1974 OrigAddr = EmitLValue(&DRE).getAddress(*this); 1975 } 1976 OMPPrivateScope VarScope(*this); 1977 VarScope.addPrivate(OrigVD, [OrigAddr]() { return OrigAddr; }); 1978 (void)VarScope.Privatize(); 1979 EmitIgnoredExpr(F); 1980 } 1981 ++IC; 1982 ++IPC; 1983 } 1984 if (DoneBB) 1985 EmitBlock(DoneBB, /*IsFinished=*/true); 1986 } 1987 1988 static void emitOMPLoopBodyWithStopPoint(CodeGenFunction &CGF, 1989 const OMPLoopDirective &S, 1990 CodeGenFunction::JumpDest LoopExit) { 1991 CGF.EmitOMPLoopBody(S, LoopExit); 1992 CGF.EmitStopPoint(&S); 1993 } 1994 1995 /// Emit a helper variable and return corresponding lvalue. 1996 static LValue EmitOMPHelperVar(CodeGenFunction &CGF, 1997 const DeclRefExpr *Helper) { 1998 auto VDecl = cast<VarDecl>(Helper->getDecl()); 1999 CGF.EmitVarDecl(*VDecl); 2000 return CGF.EmitLValue(Helper); 2001 } 2002 2003 static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S, 2004 const RegionCodeGenTy &SimdInitGen, 2005 const RegionCodeGenTy &BodyCodeGen) { 2006 auto &&ThenGen = [&S, &SimdInitGen, &BodyCodeGen](CodeGenFunction &CGF, 2007 PrePostActionTy &) { 2008 CGOpenMPRuntime::NontemporalDeclsRAII NontemporalsRegion(CGF.CGM, S); 2009 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2010 SimdInitGen(CGF); 2011 2012 BodyCodeGen(CGF); 2013 }; 2014 auto &&ElseGen = [&BodyCodeGen](CodeGenFunction &CGF, PrePostActionTy &) { 2015 CodeGenFunction::OMPLocalDeclMapRAII Scope(CGF); 2016 CGF.LoopStack.setVectorizeEnable(/*Enable=*/false); 2017 2018 BodyCodeGen(CGF); 2019 }; 2020 const Expr *IfCond = nullptr; 2021 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2022 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 2023 if (CGF.getLangOpts().OpenMP >= 50 && 2024 (C->getNameModifier() == OMPD_unknown || 2025 C->getNameModifier() == OMPD_simd)) { 2026 IfCond = C->getCondition(); 2027 break; 2028 } 2029 } 2030 } 2031 if (IfCond) { 2032 CGF.CGM.getOpenMPRuntime().emitIfClause(CGF, IfCond, ThenGen, ElseGen); 2033 } else { 2034 RegionCodeGenTy ThenRCG(ThenGen); 2035 ThenRCG(CGF); 2036 } 2037 } 2038 2039 static void emitOMPSimdRegion(CodeGenFunction &CGF, const OMPLoopDirective &S, 2040 PrePostActionTy &Action) { 2041 Action.Enter(CGF); 2042 assert(isOpenMPSimdDirective(S.getDirectiveKind()) && 2043 "Expected simd directive"); 2044 OMPLoopScope PreInitScope(CGF, S); 2045 // if (PreCond) { 2046 // for (IV in 0..LastIteration) BODY; 2047 // <Final counter/linear vars updates>; 2048 // } 2049 // 2050 if (isOpenMPDistributeDirective(S.getDirectiveKind()) || 2051 isOpenMPWorksharingDirective(S.getDirectiveKind()) || 2052 isOpenMPTaskLoopDirective(S.getDirectiveKind())) { 2053 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable())); 2054 (void)EmitOMPHelperVar(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable())); 2055 } 2056 2057 // Emit: if (PreCond) - begin. 2058 // If the condition constant folds and can be elided, avoid emitting the 2059 // whole loop. 2060 bool CondConstant; 2061 llvm::BasicBlock *ContBlock = nullptr; 2062 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2063 if (!CondConstant) 2064 return; 2065 } else { 2066 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("simd.if.then"); 2067 ContBlock = CGF.createBasicBlock("simd.if.end"); 2068 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 2069 CGF.getProfileCount(&S)); 2070 CGF.EmitBlock(ThenBlock); 2071 CGF.incrementProfileCounter(&S); 2072 } 2073 2074 // Emit the loop iteration variable. 2075 const Expr *IVExpr = S.getIterationVariable(); 2076 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 2077 CGF.EmitVarDecl(*IVDecl); 2078 CGF.EmitIgnoredExpr(S.getInit()); 2079 2080 // Emit the iterations count variable. 2081 // If it is not a variable, Sema decided to calculate iterations count on 2082 // each iteration (e.g., it is foldable into a constant). 2083 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2084 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2085 // Emit calculation of the iterations count. 2086 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 2087 } 2088 2089 emitAlignedClause(CGF, S); 2090 (void)CGF.EmitOMPLinearClauseInit(S); 2091 { 2092 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2093 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 2094 CGF.EmitOMPLinearClause(S, LoopScope); 2095 CGF.EmitOMPPrivateClause(S, LoopScope); 2096 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2097 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 2098 CGF, S, CGF.EmitLValue(S.getIterationVariable())); 2099 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2100 (void)LoopScope.Privatize(); 2101 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2102 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 2103 2104 emitCommonSimdLoop( 2105 CGF, S, 2106 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2107 CGF.EmitOMPSimdInit(S); 2108 }, 2109 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2110 CGF.EmitOMPInnerLoop( 2111 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 2112 [&S](CodeGenFunction &CGF) { 2113 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest()); 2114 CGF.EmitStopPoint(&S); 2115 }, 2116 [](CodeGenFunction &) {}); 2117 }); 2118 CGF.EmitOMPSimdFinal(S, [](CodeGenFunction &) { return nullptr; }); 2119 // Emit final copy of the lastprivate variables at the end of loops. 2120 if (HasLastprivateClause) 2121 CGF.EmitOMPLastprivateClauseFinal(S, /*NoFinals=*/true); 2122 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_simd); 2123 emitPostUpdateForReductionClause(CGF, S, 2124 [](CodeGenFunction &) { return nullptr; }); 2125 } 2126 CGF.EmitOMPLinearClauseFinal(S, [](CodeGenFunction &) { return nullptr; }); 2127 // Emit: if (PreCond) - end. 2128 if (ContBlock) { 2129 CGF.EmitBranch(ContBlock); 2130 CGF.EmitBlock(ContBlock, true); 2131 } 2132 } 2133 2134 void CodeGenFunction::EmitOMPSimdDirective(const OMPSimdDirective &S) { 2135 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2136 emitOMPSimdRegion(CGF, S, Action); 2137 }; 2138 { 2139 auto LPCRegion = 2140 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2141 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2142 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2143 } 2144 // Check for outer lastprivate conditional update. 2145 checkForLastprivateConditionalUpdate(*this, S); 2146 } 2147 2148 void CodeGenFunction::EmitOMPOuterLoop( 2149 bool DynamicOrOrdered, bool IsMonotonic, const OMPLoopDirective &S, 2150 CodeGenFunction::OMPPrivateScope &LoopScope, 2151 const CodeGenFunction::OMPLoopArguments &LoopArgs, 2152 const CodeGenFunction::CodeGenLoopTy &CodeGenLoop, 2153 const CodeGenFunction::CodeGenOrderedTy &CodeGenOrdered) { 2154 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2155 2156 const Expr *IVExpr = S.getIterationVariable(); 2157 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2158 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2159 2160 JumpDest LoopExit = getJumpDestInCurrentScope("omp.dispatch.end"); 2161 2162 // Start the loop with a block that tests the condition. 2163 llvm::BasicBlock *CondBlock = createBasicBlock("omp.dispatch.cond"); 2164 EmitBlock(CondBlock); 2165 const SourceRange R = S.getSourceRange(); 2166 LoopStack.push(CondBlock, SourceLocToDebugLoc(R.getBegin()), 2167 SourceLocToDebugLoc(R.getEnd())); 2168 2169 llvm::Value *BoolCondVal = nullptr; 2170 if (!DynamicOrOrdered) { 2171 // UB = min(UB, GlobalUB) or 2172 // UB = min(UB, PrevUB) for combined loop sharing constructs (e.g. 2173 // 'distribute parallel for') 2174 EmitIgnoredExpr(LoopArgs.EUB); 2175 // IV = LB 2176 EmitIgnoredExpr(LoopArgs.Init); 2177 // IV < UB 2178 BoolCondVal = EvaluateExprAsBool(LoopArgs.Cond); 2179 } else { 2180 BoolCondVal = 2181 RT.emitForNext(*this, S.getBeginLoc(), IVSize, IVSigned, LoopArgs.IL, 2182 LoopArgs.LB, LoopArgs.UB, LoopArgs.ST); 2183 } 2184 2185 // If there are any cleanups between here and the loop-exit scope, 2186 // create a block to stage a loop exit along. 2187 llvm::BasicBlock *ExitBlock = LoopExit.getBlock(); 2188 if (LoopScope.requiresCleanups()) 2189 ExitBlock = createBasicBlock("omp.dispatch.cleanup"); 2190 2191 llvm::BasicBlock *LoopBody = createBasicBlock("omp.dispatch.body"); 2192 Builder.CreateCondBr(BoolCondVal, LoopBody, ExitBlock); 2193 if (ExitBlock != LoopExit.getBlock()) { 2194 EmitBlock(ExitBlock); 2195 EmitBranchThroughCleanup(LoopExit); 2196 } 2197 EmitBlock(LoopBody); 2198 2199 // Emit "IV = LB" (in case of static schedule, we have already calculated new 2200 // LB for loop condition and emitted it above). 2201 if (DynamicOrOrdered) 2202 EmitIgnoredExpr(LoopArgs.Init); 2203 2204 // Create a block for the increment. 2205 JumpDest Continue = getJumpDestInCurrentScope("omp.dispatch.inc"); 2206 BreakContinueStack.push_back(BreakContinue(LoopExit, Continue)); 2207 2208 emitCommonSimdLoop( 2209 *this, S, 2210 [&S, IsMonotonic](CodeGenFunction &CGF, PrePostActionTy &) { 2211 // Generate !llvm.loop.parallel metadata for loads and stores for loops 2212 // with dynamic/guided scheduling and without ordered clause. 2213 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2214 CGF.LoopStack.setParallel(!IsMonotonic); 2215 if (const auto *C = S.getSingleClause<OMPOrderClause>()) 2216 if (C->getKind() == OMPC_ORDER_concurrent) 2217 CGF.LoopStack.setParallel(/*Enable=*/true); 2218 } else { 2219 CGF.EmitOMPSimdInit(S, IsMonotonic); 2220 } 2221 }, 2222 [&S, &LoopArgs, LoopExit, &CodeGenLoop, IVSize, IVSigned, &CodeGenOrdered, 2223 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2224 SourceLocation Loc = S.getBeginLoc(); 2225 // when 'distribute' is not combined with a 'for': 2226 // while (idx <= UB) { BODY; ++idx; } 2227 // when 'distribute' is combined with a 'for' 2228 // (e.g. 'distribute parallel for') 2229 // while (idx <= UB) { <CodeGen rest of pragma>; idx += ST; } 2230 CGF.EmitOMPInnerLoop( 2231 S, LoopScope.requiresCleanups(), LoopArgs.Cond, LoopArgs.IncExpr, 2232 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 2233 CodeGenLoop(CGF, S, LoopExit); 2234 }, 2235 [IVSize, IVSigned, Loc, &CodeGenOrdered](CodeGenFunction &CGF) { 2236 CodeGenOrdered(CGF, Loc, IVSize, IVSigned); 2237 }); 2238 }); 2239 2240 EmitBlock(Continue.getBlock()); 2241 BreakContinueStack.pop_back(); 2242 if (!DynamicOrOrdered) { 2243 // Emit "LB = LB + Stride", "UB = UB + Stride". 2244 EmitIgnoredExpr(LoopArgs.NextLB); 2245 EmitIgnoredExpr(LoopArgs.NextUB); 2246 } 2247 2248 EmitBranch(CondBlock); 2249 LoopStack.pop(); 2250 // Emit the fall-through block. 2251 EmitBlock(LoopExit.getBlock()); 2252 2253 // Tell the runtime we are done. 2254 auto &&CodeGen = [DynamicOrOrdered, &S](CodeGenFunction &CGF) { 2255 if (!DynamicOrOrdered) 2256 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 2257 S.getDirectiveKind()); 2258 }; 2259 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2260 } 2261 2262 void CodeGenFunction::EmitOMPForOuterLoop( 2263 const OpenMPScheduleTy &ScheduleKind, bool IsMonotonic, 2264 const OMPLoopDirective &S, OMPPrivateScope &LoopScope, bool Ordered, 2265 const OMPLoopArguments &LoopArgs, 2266 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 2267 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2268 2269 // Dynamic scheduling of the outer loop (dynamic, guided, auto, runtime). 2270 const bool DynamicOrOrdered = 2271 Ordered || RT.isDynamic(ScheduleKind.Schedule); 2272 2273 assert((Ordered || 2274 !RT.isStaticNonchunked(ScheduleKind.Schedule, 2275 LoopArgs.Chunk != nullptr)) && 2276 "static non-chunked schedule does not need outer loop"); 2277 2278 // Emit outer loop. 2279 // 2280 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2281 // When schedule(dynamic,chunk_size) is specified, the iterations are 2282 // distributed to threads in the team in chunks as the threads request them. 2283 // Each thread executes a chunk of iterations, then requests another chunk, 2284 // until no chunks remain to be distributed. Each chunk contains chunk_size 2285 // iterations, except for the last chunk to be distributed, which may have 2286 // fewer iterations. When no chunk_size is specified, it defaults to 1. 2287 // 2288 // When schedule(guided,chunk_size) is specified, the iterations are assigned 2289 // to threads in the team in chunks as the executing threads request them. 2290 // Each thread executes a chunk of iterations, then requests another chunk, 2291 // until no chunks remain to be assigned. For a chunk_size of 1, the size of 2292 // each chunk is proportional to the number of unassigned iterations divided 2293 // by the number of threads in the team, decreasing to 1. For a chunk_size 2294 // with value k (greater than 1), the size of each chunk is determined in the 2295 // same way, with the restriction that the chunks do not contain fewer than k 2296 // iterations (except for the last chunk to be assigned, which may have fewer 2297 // than k iterations). 2298 // 2299 // When schedule(auto) is specified, the decision regarding scheduling is 2300 // delegated to the compiler and/or runtime system. The programmer gives the 2301 // implementation the freedom to choose any possible mapping of iterations to 2302 // threads in the team. 2303 // 2304 // When schedule(runtime) is specified, the decision regarding scheduling is 2305 // deferred until run time, and the schedule and chunk size are taken from the 2306 // run-sched-var ICV. If the ICV is set to auto, the schedule is 2307 // implementation defined 2308 // 2309 // while(__kmpc_dispatch_next(&LB, &UB)) { 2310 // idx = LB; 2311 // while (idx <= UB) { BODY; ++idx; 2312 // __kmpc_dispatch_fini_(4|8)[u](); // For ordered loops only. 2313 // } // inner loop 2314 // } 2315 // 2316 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2317 // When schedule(static, chunk_size) is specified, iterations are divided into 2318 // chunks of size chunk_size, and the chunks are assigned to the threads in 2319 // the team in a round-robin fashion in the order of the thread number. 2320 // 2321 // while(UB = min(UB, GlobalUB), idx = LB, idx < UB) { 2322 // while (idx <= UB) { BODY; ++idx; } // inner loop 2323 // LB = LB + ST; 2324 // UB = UB + ST; 2325 // } 2326 // 2327 2328 const Expr *IVExpr = S.getIterationVariable(); 2329 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2330 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2331 2332 if (DynamicOrOrdered) { 2333 const std::pair<llvm::Value *, llvm::Value *> DispatchBounds = 2334 CGDispatchBounds(*this, S, LoopArgs.LB, LoopArgs.UB); 2335 llvm::Value *LBVal = DispatchBounds.first; 2336 llvm::Value *UBVal = DispatchBounds.second; 2337 CGOpenMPRuntime::DispatchRTInput DipatchRTInputValues = {LBVal, UBVal, 2338 LoopArgs.Chunk}; 2339 RT.emitForDispatchInit(*this, S.getBeginLoc(), ScheduleKind, IVSize, 2340 IVSigned, Ordered, DipatchRTInputValues); 2341 } else { 2342 CGOpenMPRuntime::StaticRTInput StaticInit( 2343 IVSize, IVSigned, Ordered, LoopArgs.IL, LoopArgs.LB, LoopArgs.UB, 2344 LoopArgs.ST, LoopArgs.Chunk); 2345 RT.emitForStaticInit(*this, S.getBeginLoc(), S.getDirectiveKind(), 2346 ScheduleKind, StaticInit); 2347 } 2348 2349 auto &&CodeGenOrdered = [Ordered](CodeGenFunction &CGF, SourceLocation Loc, 2350 const unsigned IVSize, 2351 const bool IVSigned) { 2352 if (Ordered) { 2353 CGF.CGM.getOpenMPRuntime().emitForOrderedIterationEnd(CGF, Loc, IVSize, 2354 IVSigned); 2355 } 2356 }; 2357 2358 OMPLoopArguments OuterLoopArgs(LoopArgs.LB, LoopArgs.UB, LoopArgs.ST, 2359 LoopArgs.IL, LoopArgs.Chunk, LoopArgs.EUB); 2360 OuterLoopArgs.IncExpr = S.getInc(); 2361 OuterLoopArgs.Init = S.getInit(); 2362 OuterLoopArgs.Cond = S.getCond(); 2363 OuterLoopArgs.NextLB = S.getNextLowerBound(); 2364 OuterLoopArgs.NextUB = S.getNextUpperBound(); 2365 EmitOMPOuterLoop(DynamicOrOrdered, IsMonotonic, S, LoopScope, OuterLoopArgs, 2366 emitOMPLoopBodyWithStopPoint, CodeGenOrdered); 2367 } 2368 2369 static void emitEmptyOrdered(CodeGenFunction &, SourceLocation Loc, 2370 const unsigned IVSize, const bool IVSigned) {} 2371 2372 void CodeGenFunction::EmitOMPDistributeOuterLoop( 2373 OpenMPDistScheduleClauseKind ScheduleKind, const OMPLoopDirective &S, 2374 OMPPrivateScope &LoopScope, const OMPLoopArguments &LoopArgs, 2375 const CodeGenLoopTy &CodeGenLoopContent) { 2376 2377 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2378 2379 // Emit outer loop. 2380 // Same behavior as a OMPForOuterLoop, except that schedule cannot be 2381 // dynamic 2382 // 2383 2384 const Expr *IVExpr = S.getIterationVariable(); 2385 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2386 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2387 2388 CGOpenMPRuntime::StaticRTInput StaticInit( 2389 IVSize, IVSigned, /* Ordered = */ false, LoopArgs.IL, LoopArgs.LB, 2390 LoopArgs.UB, LoopArgs.ST, LoopArgs.Chunk); 2391 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, StaticInit); 2392 2393 // for combined 'distribute' and 'for' the increment expression of distribute 2394 // is stored in DistInc. For 'distribute' alone, it is in Inc. 2395 Expr *IncExpr; 2396 if (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind())) 2397 IncExpr = S.getDistInc(); 2398 else 2399 IncExpr = S.getInc(); 2400 2401 // this routine is shared by 'omp distribute parallel for' and 2402 // 'omp distribute': select the right EUB expression depending on the 2403 // directive 2404 OMPLoopArguments OuterLoopArgs; 2405 OuterLoopArgs.LB = LoopArgs.LB; 2406 OuterLoopArgs.UB = LoopArgs.UB; 2407 OuterLoopArgs.ST = LoopArgs.ST; 2408 OuterLoopArgs.IL = LoopArgs.IL; 2409 OuterLoopArgs.Chunk = LoopArgs.Chunk; 2410 OuterLoopArgs.EUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2411 ? S.getCombinedEnsureUpperBound() 2412 : S.getEnsureUpperBound(); 2413 OuterLoopArgs.IncExpr = IncExpr; 2414 OuterLoopArgs.Init = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2415 ? S.getCombinedInit() 2416 : S.getInit(); 2417 OuterLoopArgs.Cond = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2418 ? S.getCombinedCond() 2419 : S.getCond(); 2420 OuterLoopArgs.NextLB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2421 ? S.getCombinedNextLowerBound() 2422 : S.getNextLowerBound(); 2423 OuterLoopArgs.NextUB = isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 2424 ? S.getCombinedNextUpperBound() 2425 : S.getNextUpperBound(); 2426 2427 EmitOMPOuterLoop(/* DynamicOrOrdered = */ false, /* IsMonotonic = */ false, S, 2428 LoopScope, OuterLoopArgs, CodeGenLoopContent, 2429 emitEmptyOrdered); 2430 } 2431 2432 static std::pair<LValue, LValue> 2433 emitDistributeParallelForInnerBounds(CodeGenFunction &CGF, 2434 const OMPExecutableDirective &S) { 2435 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2436 LValue LB = 2437 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 2438 LValue UB = 2439 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 2440 2441 // When composing 'distribute' with 'for' (e.g. as in 'distribute 2442 // parallel for') we need to use the 'distribute' 2443 // chunk lower and upper bounds rather than the whole loop iteration 2444 // space. These are parameters to the outlined function for 'parallel' 2445 // and we copy the bounds of the previous schedule into the 2446 // the current ones. 2447 LValue PrevLB = CGF.EmitLValue(LS.getPrevLowerBoundVariable()); 2448 LValue PrevUB = CGF.EmitLValue(LS.getPrevUpperBoundVariable()); 2449 llvm::Value *PrevLBVal = CGF.EmitLoadOfScalar( 2450 PrevLB, LS.getPrevLowerBoundVariable()->getExprLoc()); 2451 PrevLBVal = CGF.EmitScalarConversion( 2452 PrevLBVal, LS.getPrevLowerBoundVariable()->getType(), 2453 LS.getIterationVariable()->getType(), 2454 LS.getPrevLowerBoundVariable()->getExprLoc()); 2455 llvm::Value *PrevUBVal = CGF.EmitLoadOfScalar( 2456 PrevUB, LS.getPrevUpperBoundVariable()->getExprLoc()); 2457 PrevUBVal = CGF.EmitScalarConversion( 2458 PrevUBVal, LS.getPrevUpperBoundVariable()->getType(), 2459 LS.getIterationVariable()->getType(), 2460 LS.getPrevUpperBoundVariable()->getExprLoc()); 2461 2462 CGF.EmitStoreOfScalar(PrevLBVal, LB); 2463 CGF.EmitStoreOfScalar(PrevUBVal, UB); 2464 2465 return {LB, UB}; 2466 } 2467 2468 /// if the 'for' loop has a dispatch schedule (e.g. dynamic, guided) then 2469 /// we need to use the LB and UB expressions generated by the worksharing 2470 /// code generation support, whereas in non combined situations we would 2471 /// just emit 0 and the LastIteration expression 2472 /// This function is necessary due to the difference of the LB and UB 2473 /// types for the RT emission routines for 'for_static_init' and 2474 /// 'for_dispatch_init' 2475 static std::pair<llvm::Value *, llvm::Value *> 2476 emitDistributeParallelForDispatchBounds(CodeGenFunction &CGF, 2477 const OMPExecutableDirective &S, 2478 Address LB, Address UB) { 2479 const OMPLoopDirective &LS = cast<OMPLoopDirective>(S); 2480 const Expr *IVExpr = LS.getIterationVariable(); 2481 // when implementing a dynamic schedule for a 'for' combined with a 2482 // 'distribute' (e.g. 'distribute parallel for'), the 'for' loop 2483 // is not normalized as each team only executes its own assigned 2484 // distribute chunk 2485 QualType IteratorTy = IVExpr->getType(); 2486 llvm::Value *LBVal = 2487 CGF.EmitLoadOfScalar(LB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2488 llvm::Value *UBVal = 2489 CGF.EmitLoadOfScalar(UB, /*Volatile=*/false, IteratorTy, S.getBeginLoc()); 2490 return {LBVal, UBVal}; 2491 } 2492 2493 static void emitDistributeParallelForDistributeInnerBoundParams( 2494 CodeGenFunction &CGF, const OMPExecutableDirective &S, 2495 llvm::SmallVectorImpl<llvm::Value *> &CapturedVars) { 2496 const auto &Dir = cast<OMPLoopDirective>(S); 2497 LValue LB = 2498 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedLowerBoundVariable())); 2499 llvm::Value *LBCast = 2500 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(LB.getAddress(CGF)), 2501 CGF.SizeTy, /*isSigned=*/false); 2502 CapturedVars.push_back(LBCast); 2503 LValue UB = 2504 CGF.EmitLValue(cast<DeclRefExpr>(Dir.getCombinedUpperBoundVariable())); 2505 2506 llvm::Value *UBCast = 2507 CGF.Builder.CreateIntCast(CGF.Builder.CreateLoad(UB.getAddress(CGF)), 2508 CGF.SizeTy, /*isSigned=*/false); 2509 CapturedVars.push_back(UBCast); 2510 } 2511 2512 static void 2513 emitInnerParallelForWhenCombined(CodeGenFunction &CGF, 2514 const OMPLoopDirective &S, 2515 CodeGenFunction::JumpDest LoopExit) { 2516 auto &&CGInlinedWorksharingLoop = [&S](CodeGenFunction &CGF, 2517 PrePostActionTy &Action) { 2518 Action.Enter(CGF); 2519 bool HasCancel = false; 2520 if (!isOpenMPSimdDirective(S.getDirectiveKind())) { 2521 if (const auto *D = dyn_cast<OMPTeamsDistributeParallelForDirective>(&S)) 2522 HasCancel = D->hasCancel(); 2523 else if (const auto *D = dyn_cast<OMPDistributeParallelForDirective>(&S)) 2524 HasCancel = D->hasCancel(); 2525 else if (const auto *D = 2526 dyn_cast<OMPTargetTeamsDistributeParallelForDirective>(&S)) 2527 HasCancel = D->hasCancel(); 2528 } 2529 CodeGenFunction::OMPCancelStackRAII CancelRegion(CGF, S.getDirectiveKind(), 2530 HasCancel); 2531 CGF.EmitOMPWorksharingLoop(S, S.getPrevEnsureUpperBound(), 2532 emitDistributeParallelForInnerBounds, 2533 emitDistributeParallelForDispatchBounds); 2534 }; 2535 2536 emitCommonOMPParallelDirective( 2537 CGF, S, 2538 isOpenMPSimdDirective(S.getDirectiveKind()) ? OMPD_for_simd : OMPD_for, 2539 CGInlinedWorksharingLoop, 2540 emitDistributeParallelForDistributeInnerBoundParams); 2541 } 2542 2543 void CodeGenFunction::EmitOMPDistributeParallelForDirective( 2544 const OMPDistributeParallelForDirective &S) { 2545 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2546 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 2547 S.getDistInc()); 2548 }; 2549 OMPLexicalScope Scope(*this, S, OMPD_parallel); 2550 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 2551 } 2552 2553 void CodeGenFunction::EmitOMPDistributeParallelForSimdDirective( 2554 const OMPDistributeParallelForSimdDirective &S) { 2555 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2556 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 2557 S.getDistInc()); 2558 }; 2559 OMPLexicalScope Scope(*this, S, OMPD_parallel); 2560 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 2561 } 2562 2563 void CodeGenFunction::EmitOMPDistributeSimdDirective( 2564 const OMPDistributeSimdDirective &S) { 2565 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2566 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 2567 }; 2568 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2569 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2570 } 2571 2572 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction( 2573 CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) { 2574 // Emit SPMD target parallel for region as a standalone region. 2575 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2576 emitOMPSimdRegion(CGF, S, Action); 2577 }; 2578 llvm::Function *Fn; 2579 llvm::Constant *Addr; 2580 // Emit target region as a standalone region. 2581 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 2582 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 2583 assert(Fn && Addr && "Target device function emission failed."); 2584 } 2585 2586 void CodeGenFunction::EmitOMPTargetSimdDirective( 2587 const OMPTargetSimdDirective &S) { 2588 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 2589 emitOMPSimdRegion(CGF, S, Action); 2590 }; 2591 emitCommonOMPTargetDirective(*this, S, CodeGen); 2592 } 2593 2594 namespace { 2595 struct ScheduleKindModifiersTy { 2596 OpenMPScheduleClauseKind Kind; 2597 OpenMPScheduleClauseModifier M1; 2598 OpenMPScheduleClauseModifier M2; 2599 ScheduleKindModifiersTy(OpenMPScheduleClauseKind Kind, 2600 OpenMPScheduleClauseModifier M1, 2601 OpenMPScheduleClauseModifier M2) 2602 : Kind(Kind), M1(M1), M2(M2) {} 2603 }; 2604 } // namespace 2605 2606 bool CodeGenFunction::EmitOMPWorksharingLoop( 2607 const OMPLoopDirective &S, Expr *EUB, 2608 const CodeGenLoopBoundsTy &CodeGenLoopBounds, 2609 const CodeGenDispatchBoundsTy &CGDispatchBounds) { 2610 // Emit the loop iteration variable. 2611 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 2612 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 2613 EmitVarDecl(*IVDecl); 2614 2615 // Emit the iterations count variable. 2616 // If it is not a variable, Sema decided to calculate iterations count on each 2617 // iteration (e.g., it is foldable into a constant). 2618 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 2619 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 2620 // Emit calculation of the iterations count. 2621 EmitIgnoredExpr(S.getCalcLastIteration()); 2622 } 2623 2624 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 2625 2626 bool HasLastprivateClause; 2627 // Check pre-condition. 2628 { 2629 OMPLoopScope PreInitScope(*this, S); 2630 // Skip the entire loop if we don't meet the precondition. 2631 // If the condition constant folds and can be elided, avoid emitting the 2632 // whole loop. 2633 bool CondConstant; 2634 llvm::BasicBlock *ContBlock = nullptr; 2635 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 2636 if (!CondConstant) 2637 return false; 2638 } else { 2639 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 2640 ContBlock = createBasicBlock("omp.precond.end"); 2641 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 2642 getProfileCount(&S)); 2643 EmitBlock(ThenBlock); 2644 incrementProfileCounter(&S); 2645 } 2646 2647 RunCleanupsScope DoacrossCleanupScope(*this); 2648 bool Ordered = false; 2649 if (const auto *OrderedClause = S.getSingleClause<OMPOrderedClause>()) { 2650 if (OrderedClause->getNumForLoops()) 2651 RT.emitDoacrossInit(*this, S, OrderedClause->getLoopNumIterations()); 2652 else 2653 Ordered = true; 2654 } 2655 2656 llvm::DenseSet<const Expr *> EmittedFinals; 2657 emitAlignedClause(*this, S); 2658 bool HasLinears = EmitOMPLinearClauseInit(S); 2659 // Emit helper vars inits. 2660 2661 std::pair<LValue, LValue> Bounds = CodeGenLoopBounds(*this, S); 2662 LValue LB = Bounds.first; 2663 LValue UB = Bounds.second; 2664 LValue ST = 2665 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 2666 LValue IL = 2667 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 2668 2669 // Emit 'then' code. 2670 { 2671 OMPPrivateScope LoopScope(*this); 2672 if (EmitOMPFirstprivateClause(S, LoopScope) || HasLinears) { 2673 // Emit implicit barrier to synchronize threads and avoid data races on 2674 // initialization of firstprivate variables and post-update of 2675 // lastprivate variables. 2676 CGM.getOpenMPRuntime().emitBarrierCall( 2677 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 2678 /*ForceSimpleCall=*/true); 2679 } 2680 EmitOMPPrivateClause(S, LoopScope); 2681 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion( 2682 *this, S, EmitLValue(S.getIterationVariable())); 2683 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 2684 EmitOMPReductionClauseInit(S, LoopScope); 2685 EmitOMPPrivateLoopCounters(S, LoopScope); 2686 EmitOMPLinearClause(S, LoopScope); 2687 (void)LoopScope.Privatize(); 2688 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2689 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 2690 2691 // Detect the loop schedule kind and chunk. 2692 const Expr *ChunkExpr = nullptr; 2693 OpenMPScheduleTy ScheduleKind; 2694 if (const auto *C = S.getSingleClause<OMPScheduleClause>()) { 2695 ScheduleKind.Schedule = C->getScheduleKind(); 2696 ScheduleKind.M1 = C->getFirstScheduleModifier(); 2697 ScheduleKind.M2 = C->getSecondScheduleModifier(); 2698 ChunkExpr = C->getChunkSize(); 2699 } else { 2700 // Default behaviour for schedule clause. 2701 CGM.getOpenMPRuntime().getDefaultScheduleAndChunk( 2702 *this, S, ScheduleKind.Schedule, ChunkExpr); 2703 } 2704 bool HasChunkSizeOne = false; 2705 llvm::Value *Chunk = nullptr; 2706 if (ChunkExpr) { 2707 Chunk = EmitScalarExpr(ChunkExpr); 2708 Chunk = EmitScalarConversion(Chunk, ChunkExpr->getType(), 2709 S.getIterationVariable()->getType(), 2710 S.getBeginLoc()); 2711 Expr::EvalResult Result; 2712 if (ChunkExpr->EvaluateAsInt(Result, getContext())) { 2713 llvm::APSInt EvaluatedChunk = Result.Val.getInt(); 2714 HasChunkSizeOne = (EvaluatedChunk.getLimitedValue() == 1); 2715 } 2716 } 2717 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 2718 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 2719 // OpenMP 4.5, 2.7.1 Loop Construct, Description. 2720 // If the static schedule kind is specified or if the ordered clause is 2721 // specified, and if no monotonic modifier is specified, the effect will 2722 // be as if the monotonic modifier was specified. 2723 bool StaticChunkedOne = RT.isStaticChunked(ScheduleKind.Schedule, 2724 /* Chunked */ Chunk != nullptr) && HasChunkSizeOne && 2725 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 2726 if ((RT.isStaticNonchunked(ScheduleKind.Schedule, 2727 /* Chunked */ Chunk != nullptr) || 2728 StaticChunkedOne) && 2729 !Ordered) { 2730 JumpDest LoopExit = 2731 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 2732 emitCommonSimdLoop( 2733 *this, S, 2734 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 2735 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2736 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true); 2737 } else if (const auto *C = S.getSingleClause<OMPOrderClause>()) { 2738 if (C->getKind() == OMPC_ORDER_concurrent) 2739 CGF.LoopStack.setParallel(/*Enable=*/true); 2740 } 2741 }, 2742 [IVSize, IVSigned, Ordered, IL, LB, UB, ST, StaticChunkedOne, Chunk, 2743 &S, ScheduleKind, LoopExit, 2744 &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 2745 // OpenMP [2.7.1, Loop Construct, Description, table 2-1] 2746 // When no chunk_size is specified, the iteration space is divided 2747 // into chunks that are approximately equal in size, and at most 2748 // one chunk is distributed to each thread. Note that the size of 2749 // the chunks is unspecified in this case. 2750 CGOpenMPRuntime::StaticRTInput StaticInit( 2751 IVSize, IVSigned, Ordered, IL.getAddress(CGF), 2752 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF), 2753 StaticChunkedOne ? Chunk : nullptr); 2754 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 2755 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, 2756 StaticInit); 2757 // UB = min(UB, GlobalUB); 2758 if (!StaticChunkedOne) 2759 CGF.EmitIgnoredExpr(S.getEnsureUpperBound()); 2760 // IV = LB; 2761 CGF.EmitIgnoredExpr(S.getInit()); 2762 // For unchunked static schedule generate: 2763 // 2764 // while (idx <= UB) { 2765 // BODY; 2766 // ++idx; 2767 // } 2768 // 2769 // For static schedule with chunk one: 2770 // 2771 // while (IV <= PrevUB) { 2772 // BODY; 2773 // IV += ST; 2774 // } 2775 CGF.EmitOMPInnerLoop( 2776 S, LoopScope.requiresCleanups(), 2777 StaticChunkedOne ? S.getCombinedParForInDistCond() 2778 : S.getCond(), 2779 StaticChunkedOne ? S.getDistInc() : S.getInc(), 2780 [&S, LoopExit](CodeGenFunction &CGF) { 2781 CGF.EmitOMPLoopBody(S, LoopExit); 2782 CGF.EmitStopPoint(&S); 2783 }, 2784 [](CodeGenFunction &) {}); 2785 }); 2786 EmitBlock(LoopExit.getBlock()); 2787 // Tell the runtime we are done. 2788 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 2789 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 2790 S.getDirectiveKind()); 2791 }; 2792 OMPCancelStack.emitExit(*this, S.getDirectiveKind(), CodeGen); 2793 } else { 2794 const bool IsMonotonic = 2795 Ordered || ScheduleKind.Schedule == OMPC_SCHEDULE_static || 2796 ScheduleKind.Schedule == OMPC_SCHEDULE_unknown || 2797 ScheduleKind.M1 == OMPC_SCHEDULE_MODIFIER_monotonic || 2798 ScheduleKind.M2 == OMPC_SCHEDULE_MODIFIER_monotonic; 2799 // Emit the outer loop, which requests its work chunk [LB..UB] from 2800 // runtime and runs the inner loop to process it. 2801 const OMPLoopArguments LoopArguments( 2802 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 2803 IL.getAddress(*this), Chunk, EUB); 2804 EmitOMPForOuterLoop(ScheduleKind, IsMonotonic, S, LoopScope, Ordered, 2805 LoopArguments, CGDispatchBounds); 2806 } 2807 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 2808 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 2809 return CGF.Builder.CreateIsNotNull( 2810 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 2811 }); 2812 } 2813 EmitOMPReductionClauseFinal( 2814 S, /*ReductionKind=*/isOpenMPSimdDirective(S.getDirectiveKind()) 2815 ? /*Parallel and Simd*/ OMPD_parallel_for_simd 2816 : /*Parallel only*/ OMPD_parallel); 2817 // Emit post-update of the reduction variables if IsLastIter != 0. 2818 emitPostUpdateForReductionClause( 2819 *this, S, [IL, &S](CodeGenFunction &CGF) { 2820 return CGF.Builder.CreateIsNotNull( 2821 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 2822 }); 2823 // Emit final copy of the lastprivate variables if IsLastIter != 0. 2824 if (HasLastprivateClause) 2825 EmitOMPLastprivateClauseFinal( 2826 S, isOpenMPSimdDirective(S.getDirectiveKind()), 2827 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 2828 } 2829 EmitOMPLinearClauseFinal(S, [IL, &S](CodeGenFunction &CGF) { 2830 return CGF.Builder.CreateIsNotNull( 2831 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 2832 }); 2833 DoacrossCleanupScope.ForceCleanup(); 2834 // We're now done with the loop, so jump to the continuation block. 2835 if (ContBlock) { 2836 EmitBranch(ContBlock); 2837 EmitBlock(ContBlock, /*IsFinished=*/true); 2838 } 2839 } 2840 return HasLastprivateClause; 2841 } 2842 2843 /// The following two functions generate expressions for the loop lower 2844 /// and upper bounds in case of static and dynamic (dispatch) schedule 2845 /// of the associated 'for' or 'distribute' loop. 2846 static std::pair<LValue, LValue> 2847 emitForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 2848 const auto &LS = cast<OMPLoopDirective>(S); 2849 LValue LB = 2850 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getLowerBoundVariable())); 2851 LValue UB = 2852 EmitOMPHelperVar(CGF, cast<DeclRefExpr>(LS.getUpperBoundVariable())); 2853 return {LB, UB}; 2854 } 2855 2856 /// When dealing with dispatch schedules (e.g. dynamic, guided) we do not 2857 /// consider the lower and upper bound expressions generated by the 2858 /// worksharing loop support, but we use 0 and the iteration space size as 2859 /// constants 2860 static std::pair<llvm::Value *, llvm::Value *> 2861 emitDispatchForLoopBounds(CodeGenFunction &CGF, const OMPExecutableDirective &S, 2862 Address LB, Address UB) { 2863 const auto &LS = cast<OMPLoopDirective>(S); 2864 const Expr *IVExpr = LS.getIterationVariable(); 2865 const unsigned IVSize = CGF.getContext().getTypeSize(IVExpr->getType()); 2866 llvm::Value *LBVal = CGF.Builder.getIntN(IVSize, 0); 2867 llvm::Value *UBVal = CGF.EmitScalarExpr(LS.getLastIteration()); 2868 return {LBVal, UBVal}; 2869 } 2870 2871 void CodeGenFunction::EmitOMPForDirective(const OMPForDirective &S) { 2872 bool HasLastprivates = false; 2873 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 2874 PrePostActionTy &) { 2875 OMPCancelStackRAII CancelRegion(CGF, OMPD_for, S.hasCancel()); 2876 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 2877 emitForLoopBounds, 2878 emitDispatchForLoopBounds); 2879 }; 2880 { 2881 auto LPCRegion = 2882 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2883 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2884 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_for, CodeGen, 2885 S.hasCancel()); 2886 } 2887 2888 // Emit an implicit barrier at the end. 2889 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 2890 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 2891 // Check for outer lastprivate conditional update. 2892 checkForLastprivateConditionalUpdate(*this, S); 2893 } 2894 2895 void CodeGenFunction::EmitOMPForSimdDirective(const OMPForSimdDirective &S) { 2896 bool HasLastprivates = false; 2897 auto &&CodeGen = [&S, &HasLastprivates](CodeGenFunction &CGF, 2898 PrePostActionTy &) { 2899 HasLastprivates = CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), 2900 emitForLoopBounds, 2901 emitDispatchForLoopBounds); 2902 }; 2903 { 2904 auto LPCRegion = 2905 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 2906 OMPLexicalScope Scope(*this, S, OMPD_unknown); 2907 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_simd, CodeGen); 2908 } 2909 2910 // Emit an implicit barrier at the end. 2911 if (!S.getSingleClause<OMPNowaitClause>() || HasLastprivates) 2912 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_for); 2913 // Check for outer lastprivate conditional update. 2914 checkForLastprivateConditionalUpdate(*this, S); 2915 } 2916 2917 static LValue createSectionLVal(CodeGenFunction &CGF, QualType Ty, 2918 const Twine &Name, 2919 llvm::Value *Init = nullptr) { 2920 LValue LVal = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty, Name), Ty); 2921 if (Init) 2922 CGF.EmitStoreThroughLValue(RValue::get(Init), LVal, /*isInit*/ true); 2923 return LVal; 2924 } 2925 2926 void CodeGenFunction::EmitSections(const OMPExecutableDirective &S) { 2927 const Stmt *CapturedStmt = S.getInnermostCapturedStmt()->getCapturedStmt(); 2928 const auto *CS = dyn_cast<CompoundStmt>(CapturedStmt); 2929 bool HasLastprivates = false; 2930 auto &&CodeGen = [&S, CapturedStmt, CS, 2931 &HasLastprivates](CodeGenFunction &CGF, PrePostActionTy &) { 2932 ASTContext &C = CGF.getContext(); 2933 QualType KmpInt32Ty = 2934 C.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2935 // Emit helper vars inits. 2936 LValue LB = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.lb.", 2937 CGF.Builder.getInt32(0)); 2938 llvm::ConstantInt *GlobalUBVal = CS != nullptr 2939 ? CGF.Builder.getInt32(CS->size() - 1) 2940 : CGF.Builder.getInt32(0); 2941 LValue UB = 2942 createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.ub.", GlobalUBVal); 2943 LValue ST = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.st.", 2944 CGF.Builder.getInt32(1)); 2945 LValue IL = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.il.", 2946 CGF.Builder.getInt32(0)); 2947 // Loop counter. 2948 LValue IV = createSectionLVal(CGF, KmpInt32Ty, ".omp.sections.iv."); 2949 OpaqueValueExpr IVRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 2950 CodeGenFunction::OpaqueValueMapping OpaqueIV(CGF, &IVRefExpr, IV); 2951 OpaqueValueExpr UBRefExpr(S.getBeginLoc(), KmpInt32Ty, VK_LValue); 2952 CodeGenFunction::OpaqueValueMapping OpaqueUB(CGF, &UBRefExpr, UB); 2953 // Generate condition for loop. 2954 BinaryOperator Cond(&IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, 2955 OK_Ordinary, S.getBeginLoc(), FPOptions()); 2956 // Increment for loop counter. 2957 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary, 2958 S.getBeginLoc(), true); 2959 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) { 2960 // Iterate through all sections and emit a switch construct: 2961 // switch (IV) { 2962 // case 0: 2963 // <SectionStmt[0]>; 2964 // break; 2965 // ... 2966 // case <NumSection> - 1: 2967 // <SectionStmt[<NumSection> - 1]>; 2968 // break; 2969 // } 2970 // .omp.sections.exit: 2971 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 2972 llvm::SwitchInst *SwitchStmt = 2973 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()), 2974 ExitBB, CS == nullptr ? 1 : CS->size()); 2975 if (CS) { 2976 unsigned CaseNumber = 0; 2977 for (const Stmt *SubStmt : CS->children()) { 2978 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2979 CGF.EmitBlock(CaseBB); 2980 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 2981 CGF.EmitStmt(SubStmt); 2982 CGF.EmitBranch(ExitBB); 2983 ++CaseNumber; 2984 } 2985 } else { 2986 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2987 CGF.EmitBlock(CaseBB); 2988 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB); 2989 CGF.EmitStmt(CapturedStmt); 2990 CGF.EmitBranch(ExitBB); 2991 } 2992 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 2993 }; 2994 2995 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2996 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 2997 // Emit implicit barrier to synchronize threads and avoid data races on 2998 // initialization of firstprivate variables and post-update of lastprivate 2999 // variables. 3000 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3001 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3002 /*ForceSimpleCall=*/true); 3003 } 3004 CGF.EmitOMPPrivateClause(S, LoopScope); 3005 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV); 3006 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 3007 CGF.EmitOMPReductionClauseInit(S, LoopScope); 3008 (void)LoopScope.Privatize(); 3009 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3010 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 3011 3012 // Emit static non-chunked loop. 3013 OpenMPScheduleTy ScheduleKind; 3014 ScheduleKind.Schedule = OMPC_SCHEDULE_static; 3015 CGOpenMPRuntime::StaticRTInput StaticInit( 3016 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF), 3017 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF)); 3018 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 3019 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit); 3020 // UB = min(UB, GlobalUB); 3021 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc()); 3022 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect( 3023 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 3024 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 3025 // IV = LB; 3026 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV); 3027 // while (idx <= UB) { BODY; ++idx; } 3028 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, &Cond, &Inc, BodyGen, 3029 [](CodeGenFunction &) {}); 3030 // Tell the runtime we are done. 3031 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3032 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3033 S.getDirectiveKind()); 3034 }; 3035 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen); 3036 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3037 // Emit post-update of the reduction variables if IsLastIter != 0. 3038 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) { 3039 return CGF.Builder.CreateIsNotNull( 3040 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3041 }); 3042 3043 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3044 if (HasLastprivates) 3045 CGF.EmitOMPLastprivateClauseFinal( 3046 S, /*NoFinals=*/false, 3047 CGF.Builder.CreateIsNotNull( 3048 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()))); 3049 }; 3050 3051 bool HasCancel = false; 3052 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S)) 3053 HasCancel = OSD->hasCancel(); 3054 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S)) 3055 HasCancel = OPSD->hasCancel(); 3056 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel); 3057 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen, 3058 HasCancel); 3059 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 3060 // clause. Otherwise the barrier will be generated by the codegen for the 3061 // directive. 3062 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) { 3063 // Emit implicit barrier to synchronize threads and avoid data races on 3064 // initialization of firstprivate variables. 3065 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3066 OMPD_unknown); 3067 } 3068 } 3069 3070 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 3071 { 3072 auto LPCRegion = 3073 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3074 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3075 EmitSections(S); 3076 } 3077 // Emit an implicit barrier at the end. 3078 if (!S.getSingleClause<OMPNowaitClause>()) { 3079 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3080 OMPD_sections); 3081 } 3082 // Check for outer lastprivate conditional update. 3083 checkForLastprivateConditionalUpdate(*this, S); 3084 } 3085 3086 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 3087 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3088 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3089 }; 3090 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3091 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen, 3092 S.hasCancel()); 3093 } 3094 3095 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 3096 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 3097 llvm::SmallVector<const Expr *, 8> DestExprs; 3098 llvm::SmallVector<const Expr *, 8> SrcExprs; 3099 llvm::SmallVector<const Expr *, 8> AssignmentOps; 3100 // Check if there are any 'copyprivate' clauses associated with this 3101 // 'single' construct. 3102 // Build a list of copyprivate variables along with helper expressions 3103 // (<source>, <destination>, <destination>=<source> expressions) 3104 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) { 3105 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 3106 DestExprs.append(C->destination_exprs().begin(), 3107 C->destination_exprs().end()); 3108 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 3109 AssignmentOps.append(C->assignment_ops().begin(), 3110 C->assignment_ops().end()); 3111 } 3112 // Emit code for 'single' region along with 'copyprivate' clauses 3113 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3114 Action.Enter(CGF); 3115 OMPPrivateScope SingleScope(CGF); 3116 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope); 3117 CGF.EmitOMPPrivateClause(S, SingleScope); 3118 (void)SingleScope.Privatize(); 3119 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3120 }; 3121 { 3122 auto LPCRegion = 3123 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3124 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3125 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(), 3126 CopyprivateVars, DestExprs, 3127 SrcExprs, AssignmentOps); 3128 } 3129 // Emit an implicit barrier at the end (to avoid data race on firstprivate 3130 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 3131 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) { 3132 CGM.getOpenMPRuntime().emitBarrierCall( 3133 *this, S.getBeginLoc(), 3134 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single); 3135 } 3136 // Check for outer lastprivate conditional update. 3137 checkForLastprivateConditionalUpdate(*this, S); 3138 } 3139 3140 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3141 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3142 Action.Enter(CGF); 3143 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3144 }; 3145 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 3146 } 3147 3148 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 3149 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3150 emitMaster(*this, S); 3151 } 3152 3153 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 3154 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3155 Action.Enter(CGF); 3156 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3157 }; 3158 const Expr *Hint = nullptr; 3159 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 3160 Hint = HintClause->getHint(); 3161 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3162 CGM.getOpenMPRuntime().emitCriticalRegion(*this, 3163 S.getDirectiveName().getAsString(), 3164 CodeGen, S.getBeginLoc(), Hint); 3165 } 3166 3167 void CodeGenFunction::EmitOMPParallelForDirective( 3168 const OMPParallelForDirective &S) { 3169 // Emit directive as a combined directive that consists of two implicit 3170 // directives: 'parallel' with 'for' directive. 3171 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3172 Action.Enter(CGF); 3173 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel()); 3174 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 3175 emitDispatchForLoopBounds); 3176 }; 3177 { 3178 auto LPCRegion = 3179 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3180 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen, 3181 emitEmptyBoundParameters); 3182 } 3183 // Check for outer lastprivate conditional update. 3184 checkForLastprivateConditionalUpdate(*this, S); 3185 } 3186 3187 void CodeGenFunction::EmitOMPParallelForSimdDirective( 3188 const OMPParallelForSimdDirective &S) { 3189 // Emit directive as a combined directive that consists of two implicit 3190 // directives: 'parallel' with 'for' directive. 3191 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3192 Action.Enter(CGF); 3193 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 3194 emitDispatchForLoopBounds); 3195 }; 3196 { 3197 auto LPCRegion = 3198 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3199 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen, 3200 emitEmptyBoundParameters); 3201 } 3202 // Check for outer lastprivate conditional update. 3203 checkForLastprivateConditionalUpdate(*this, S); 3204 } 3205 3206 void CodeGenFunction::EmitOMPParallelMasterDirective( 3207 const OMPParallelMasterDirective &S) { 3208 // Emit directive as a combined directive that consists of two implicit 3209 // directives: 'parallel' with 'master' directive. 3210 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3211 Action.Enter(CGF); 3212 OMPPrivateScope PrivateScope(CGF); 3213 bool Copyins = CGF.EmitOMPCopyinClause(S); 3214 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 3215 if (Copyins) { 3216 // Emit implicit barrier to synchronize threads and avoid data races on 3217 // propagation master's thread values of threadprivate variables to local 3218 // instances of that variables of all other implicit threads. 3219 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3220 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3221 /*ForceSimpleCall=*/true); 3222 } 3223 CGF.EmitOMPPrivateClause(S, PrivateScope); 3224 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 3225 (void)PrivateScope.Privatize(); 3226 emitMaster(CGF, S); 3227 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3228 }; 3229 { 3230 auto LPCRegion = 3231 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3232 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen, 3233 emitEmptyBoundParameters); 3234 emitPostUpdateForReductionClause(*this, S, 3235 [](CodeGenFunction &) { return nullptr; }); 3236 } 3237 // Check for outer lastprivate conditional update. 3238 checkForLastprivateConditionalUpdate(*this, S); 3239 } 3240 3241 void CodeGenFunction::EmitOMPParallelSectionsDirective( 3242 const OMPParallelSectionsDirective &S) { 3243 // Emit directive as a combined directive that consists of two implicit 3244 // directives: 'parallel' with 'sections' directive. 3245 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3246 Action.Enter(CGF); 3247 CGF.EmitSections(S); 3248 }; 3249 { 3250 auto LPCRegion = 3251 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3252 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen, 3253 emitEmptyBoundParameters); 3254 } 3255 // Check for outer lastprivate conditional update. 3256 checkForLastprivateConditionalUpdate(*this, S); 3257 } 3258 3259 void CodeGenFunction::EmitOMPTaskBasedDirective( 3260 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, 3261 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, 3262 OMPTaskDataTy &Data) { 3263 // Emit outlined function for task construct. 3264 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion); 3265 auto I = CS->getCapturedDecl()->param_begin(); 3266 auto PartId = std::next(I); 3267 auto TaskT = std::next(I, 4); 3268 // Check if the task is final 3269 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) { 3270 // If the condition constant folds and can be elided, try to avoid emitting 3271 // the condition and the dead arm of the if/else. 3272 const Expr *Cond = Clause->getCondition(); 3273 bool CondConstant; 3274 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 3275 Data.Final.setInt(CondConstant); 3276 else 3277 Data.Final.setPointer(EvaluateExprAsBool(Cond)); 3278 } else { 3279 // By default the task is not final. 3280 Data.Final.setInt(/*IntVal=*/false); 3281 } 3282 // Check if the task has 'priority' clause. 3283 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) { 3284 const Expr *Prio = Clause->getPriority(); 3285 Data.Priority.setInt(/*IntVal=*/true); 3286 Data.Priority.setPointer(EmitScalarConversion( 3287 EmitScalarExpr(Prio), Prio->getType(), 3288 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), 3289 Prio->getExprLoc())); 3290 } 3291 // The first function argument for tasks is a thread id, the second one is a 3292 // part id (0 for tied tasks, >=0 for untied task). 3293 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 3294 // Get list of private variables. 3295 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 3296 auto IRef = C->varlist_begin(); 3297 for (const Expr *IInit : C->private_copies()) { 3298 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3299 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3300 Data.PrivateVars.push_back(*IRef); 3301 Data.PrivateCopies.push_back(IInit); 3302 } 3303 ++IRef; 3304 } 3305 } 3306 EmittedAsPrivate.clear(); 3307 // Get list of firstprivate variables. 3308 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 3309 auto IRef = C->varlist_begin(); 3310 auto IElemInitRef = C->inits().begin(); 3311 for (const Expr *IInit : C->private_copies()) { 3312 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3313 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3314 Data.FirstprivateVars.push_back(*IRef); 3315 Data.FirstprivateCopies.push_back(IInit); 3316 Data.FirstprivateInits.push_back(*IElemInitRef); 3317 } 3318 ++IRef; 3319 ++IElemInitRef; 3320 } 3321 } 3322 // Get list of lastprivate variables (for taskloops). 3323 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs; 3324 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 3325 auto IRef = C->varlist_begin(); 3326 auto ID = C->destination_exprs().begin(); 3327 for (const Expr *IInit : C->private_copies()) { 3328 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3329 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3330 Data.LastprivateVars.push_back(*IRef); 3331 Data.LastprivateCopies.push_back(IInit); 3332 } 3333 LastprivateDstsOrigs.insert( 3334 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()), 3335 cast<DeclRefExpr>(*IRef)}); 3336 ++IRef; 3337 ++ID; 3338 } 3339 } 3340 SmallVector<const Expr *, 4> LHSs; 3341 SmallVector<const Expr *, 4> RHSs; 3342 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3343 auto IPriv = C->privates().begin(); 3344 auto IRed = C->reduction_ops().begin(); 3345 auto ILHS = C->lhs_exprs().begin(); 3346 auto IRHS = C->rhs_exprs().begin(); 3347 for (const Expr *Ref : C->varlists()) { 3348 Data.ReductionVars.emplace_back(Ref); 3349 Data.ReductionCopies.emplace_back(*IPriv); 3350 Data.ReductionOps.emplace_back(*IRed); 3351 LHSs.emplace_back(*ILHS); 3352 RHSs.emplace_back(*IRHS); 3353 std::advance(IPriv, 1); 3354 std::advance(IRed, 1); 3355 std::advance(ILHS, 1); 3356 std::advance(IRHS, 1); 3357 } 3358 } 3359 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit( 3360 *this, S.getBeginLoc(), LHSs, RHSs, Data); 3361 // Build list of dependences. 3362 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) 3363 for (const Expr *IRef : C->varlists()) 3364 Data.Dependences.emplace_back(C->getDependencyKind(), IRef); 3365 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs, 3366 CapturedRegion](CodeGenFunction &CGF, 3367 PrePostActionTy &Action) { 3368 // Set proper addresses for generated private copies. 3369 OMPPrivateScope Scope(CGF); 3370 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() || 3371 !Data.LastprivateVars.empty()) { 3372 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 3373 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 3374 enum { PrivatesParam = 2, CopyFnParam = 3 }; 3375 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 3376 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 3377 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 3378 CS->getCapturedDecl()->getParam(PrivatesParam))); 3379 // Map privates. 3380 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 3381 llvm::SmallVector<llvm::Value *, 16> CallArgs; 3382 CallArgs.push_back(PrivatesPtr); 3383 for (const Expr *E : Data.PrivateVars) { 3384 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3385 Address PrivatePtr = CGF.CreateMemTemp( 3386 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr"); 3387 PrivatePtrs.emplace_back(VD, PrivatePtr); 3388 CallArgs.push_back(PrivatePtr.getPointer()); 3389 } 3390 for (const Expr *E : Data.FirstprivateVars) { 3391 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3392 Address PrivatePtr = 3393 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3394 ".firstpriv.ptr.addr"); 3395 PrivatePtrs.emplace_back(VD, PrivatePtr); 3396 CallArgs.push_back(PrivatePtr.getPointer()); 3397 } 3398 for (const Expr *E : Data.LastprivateVars) { 3399 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3400 Address PrivatePtr = 3401 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3402 ".lastpriv.ptr.addr"); 3403 PrivatePtrs.emplace_back(VD, PrivatePtr); 3404 CallArgs.push_back(PrivatePtr.getPointer()); 3405 } 3406 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 3407 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 3408 for (const auto &Pair : LastprivateDstsOrigs) { 3409 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl()); 3410 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD), 3411 /*RefersToEnclosingVariableOrCapture=*/ 3412 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr, 3413 Pair.second->getType(), VK_LValue, 3414 Pair.second->getExprLoc()); 3415 Scope.addPrivate(Pair.first, [&CGF, &DRE]() { 3416 return CGF.EmitLValue(&DRE).getAddress(CGF); 3417 }); 3418 } 3419 for (const auto &Pair : PrivatePtrs) { 3420 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 3421 CGF.getContext().getDeclAlign(Pair.first)); 3422 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 3423 } 3424 } 3425 if (Data.Reductions) { 3426 OMPLexicalScope LexScope(CGF, S, CapturedRegion); 3427 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies, 3428 Data.ReductionOps); 3429 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad( 3430 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9))); 3431 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) { 3432 RedCG.emitSharedLValue(CGF, Cnt); 3433 RedCG.emitAggregateType(CGF, Cnt); 3434 // FIXME: This must removed once the runtime library is fixed. 3435 // Emit required threadprivate variables for 3436 // initializer/combiner/finalizer. 3437 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 3438 RedCG, Cnt); 3439 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 3440 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 3441 Replacement = 3442 Address(CGF.EmitScalarConversion( 3443 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 3444 CGF.getContext().getPointerType( 3445 Data.ReductionCopies[Cnt]->getType()), 3446 Data.ReductionCopies[Cnt]->getExprLoc()), 3447 Replacement.getAlignment()); 3448 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 3449 Scope.addPrivate(RedCG.getBaseDecl(Cnt), 3450 [Replacement]() { return Replacement; }); 3451 } 3452 } 3453 // Privatize all private variables except for in_reduction items. 3454 (void)Scope.Privatize(); 3455 SmallVector<const Expr *, 4> InRedVars; 3456 SmallVector<const Expr *, 4> InRedPrivs; 3457 SmallVector<const Expr *, 4> InRedOps; 3458 SmallVector<const Expr *, 4> TaskgroupDescriptors; 3459 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) { 3460 auto IPriv = C->privates().begin(); 3461 auto IRed = C->reduction_ops().begin(); 3462 auto ITD = C->taskgroup_descriptors().begin(); 3463 for (const Expr *Ref : C->varlists()) { 3464 InRedVars.emplace_back(Ref); 3465 InRedPrivs.emplace_back(*IPriv); 3466 InRedOps.emplace_back(*IRed); 3467 TaskgroupDescriptors.emplace_back(*ITD); 3468 std::advance(IPriv, 1); 3469 std::advance(IRed, 1); 3470 std::advance(ITD, 1); 3471 } 3472 } 3473 // Privatize in_reduction items here, because taskgroup descriptors must be 3474 // privatized earlier. 3475 OMPPrivateScope InRedScope(CGF); 3476 if (!InRedVars.empty()) { 3477 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps); 3478 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) { 3479 RedCG.emitSharedLValue(CGF, Cnt); 3480 RedCG.emitAggregateType(CGF, Cnt); 3481 // The taskgroup descriptor variable is always implicit firstprivate and 3482 // privatized already during processing of the firstprivates. 3483 // FIXME: This must removed once the runtime library is fixed. 3484 // Emit required threadprivate variables for 3485 // initializer/combiner/finalizer. 3486 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 3487 RedCG, Cnt); 3488 llvm::Value *ReductionsPtr = 3489 CGF.EmitLoadOfScalar(CGF.EmitLValue(TaskgroupDescriptors[Cnt]), 3490 TaskgroupDescriptors[Cnt]->getExprLoc()); 3491 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 3492 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 3493 Replacement = Address( 3494 CGF.EmitScalarConversion( 3495 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 3496 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()), 3497 InRedPrivs[Cnt]->getExprLoc()), 3498 Replacement.getAlignment()); 3499 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 3500 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), 3501 [Replacement]() { return Replacement; }); 3502 } 3503 } 3504 (void)InRedScope.Privatize(); 3505 3506 Action.Enter(CGF); 3507 BodyGen(CGF); 3508 }; 3509 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 3510 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied, 3511 Data.NumberOfParts); 3512 OMPLexicalScope Scope(*this, S, llvm::None, 3513 !isOpenMPParallelDirective(S.getDirectiveKind()) && 3514 !isOpenMPSimdDirective(S.getDirectiveKind())); 3515 TaskGen(*this, OutlinedFn, Data); 3516 } 3517 3518 static ImplicitParamDecl * 3519 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, 3520 QualType Ty, CapturedDecl *CD, 3521 SourceLocation Loc) { 3522 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 3523 ImplicitParamDecl::Other); 3524 auto *OrigRef = DeclRefExpr::Create( 3525 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD, 3526 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 3527 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 3528 ImplicitParamDecl::Other); 3529 auto *PrivateRef = DeclRefExpr::Create( 3530 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD, 3531 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 3532 QualType ElemType = C.getBaseElementType(Ty); 3533 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType, 3534 ImplicitParamDecl::Other); 3535 auto *InitRef = DeclRefExpr::Create( 3536 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD, 3537 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue); 3538 PrivateVD->setInitStyle(VarDecl::CInit); 3539 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue, 3540 InitRef, /*BasePath=*/nullptr, 3541 VK_RValue)); 3542 Data.FirstprivateVars.emplace_back(OrigRef); 3543 Data.FirstprivateCopies.emplace_back(PrivateRef); 3544 Data.FirstprivateInits.emplace_back(InitRef); 3545 return OrigVD; 3546 } 3547 3548 void CodeGenFunction::EmitOMPTargetTaskBasedDirective( 3549 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, 3550 OMPTargetDataInfo &InputInfo) { 3551 // Emit outlined function for task construct. 3552 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 3553 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 3554 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 3555 auto I = CS->getCapturedDecl()->param_begin(); 3556 auto PartId = std::next(I); 3557 auto TaskT = std::next(I, 4); 3558 OMPTaskDataTy Data; 3559 // The task is not final. 3560 Data.Final.setInt(/*IntVal=*/false); 3561 // Get list of firstprivate variables. 3562 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 3563 auto IRef = C->varlist_begin(); 3564 auto IElemInitRef = C->inits().begin(); 3565 for (auto *IInit : C->private_copies()) { 3566 Data.FirstprivateVars.push_back(*IRef); 3567 Data.FirstprivateCopies.push_back(IInit); 3568 Data.FirstprivateInits.push_back(*IElemInitRef); 3569 ++IRef; 3570 ++IElemInitRef; 3571 } 3572 } 3573 OMPPrivateScope TargetScope(*this); 3574 VarDecl *BPVD = nullptr; 3575 VarDecl *PVD = nullptr; 3576 VarDecl *SVD = nullptr; 3577 if (InputInfo.NumberOfTargetItems > 0) { 3578 auto *CD = CapturedDecl::Create( 3579 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0); 3580 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems); 3581 QualType BaseAndPointersType = getContext().getConstantArrayType( 3582 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal, 3583 /*IndexTypeQuals=*/0); 3584 BPVD = createImplicitFirstprivateForType( 3585 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc()); 3586 PVD = createImplicitFirstprivateForType( 3587 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc()); 3588 QualType SizesType = getContext().getConstantArrayType( 3589 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1), 3590 ArrSize, nullptr, ArrayType::Normal, 3591 /*IndexTypeQuals=*/0); 3592 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD, 3593 S.getBeginLoc()); 3594 TargetScope.addPrivate( 3595 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; }); 3596 TargetScope.addPrivate(PVD, 3597 [&InputInfo]() { return InputInfo.PointersArray; }); 3598 TargetScope.addPrivate(SVD, 3599 [&InputInfo]() { return InputInfo.SizesArray; }); 3600 } 3601 (void)TargetScope.Privatize(); 3602 // Build list of dependences. 3603 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) 3604 for (const Expr *IRef : C->varlists()) 3605 Data.Dependences.emplace_back(C->getDependencyKind(), IRef); 3606 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, 3607 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) { 3608 // Set proper addresses for generated private copies. 3609 OMPPrivateScope Scope(CGF); 3610 if (!Data.FirstprivateVars.empty()) { 3611 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 3612 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 3613 enum { PrivatesParam = 2, CopyFnParam = 3 }; 3614 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 3615 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 3616 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 3617 CS->getCapturedDecl()->getParam(PrivatesParam))); 3618 // Map privates. 3619 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 3620 llvm::SmallVector<llvm::Value *, 16> CallArgs; 3621 CallArgs.push_back(PrivatesPtr); 3622 for (const Expr *E : Data.FirstprivateVars) { 3623 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3624 Address PrivatePtr = 3625 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3626 ".firstpriv.ptr.addr"); 3627 PrivatePtrs.emplace_back(VD, PrivatePtr); 3628 CallArgs.push_back(PrivatePtr.getPointer()); 3629 } 3630 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 3631 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 3632 for (const auto &Pair : PrivatePtrs) { 3633 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 3634 CGF.getContext().getDeclAlign(Pair.first)); 3635 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 3636 } 3637 } 3638 // Privatize all private variables except for in_reduction items. 3639 (void)Scope.Privatize(); 3640 if (InputInfo.NumberOfTargetItems > 0) { 3641 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP( 3642 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0); 3643 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP( 3644 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0); 3645 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP( 3646 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0); 3647 } 3648 3649 Action.Enter(CGF); 3650 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false); 3651 BodyGen(CGF); 3652 }; 3653 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 3654 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true, 3655 Data.NumberOfParts); 3656 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0); 3657 IntegerLiteral IfCond(getContext(), TrueOrFalse, 3658 getContext().getIntTypeForBitwidth(32, /*Signed=*/0), 3659 SourceLocation()); 3660 3661 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn, 3662 SharedsTy, CapturedStruct, &IfCond, Data); 3663 } 3664 3665 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 3666 // Emit outlined function for task construct. 3667 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 3668 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 3669 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 3670 const Expr *IfCond = nullptr; 3671 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 3672 if (C->getNameModifier() == OMPD_unknown || 3673 C->getNameModifier() == OMPD_task) { 3674 IfCond = C->getCondition(); 3675 break; 3676 } 3677 } 3678 3679 OMPTaskDataTy Data; 3680 // Check if we should emit tied or untied task. 3681 Data.Tied = !S.getSingleClause<OMPUntiedClause>(); 3682 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) { 3683 CGF.EmitStmt(CS->getCapturedStmt()); 3684 }; 3685 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 3686 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 3687 const OMPTaskDataTy &Data) { 3688 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn, 3689 SharedsTy, CapturedStruct, IfCond, 3690 Data); 3691 }; 3692 auto LPCRegion = 3693 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3694 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data); 3695 } 3696 3697 void CodeGenFunction::EmitOMPTaskyieldDirective( 3698 const OMPTaskyieldDirective &S) { 3699 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc()); 3700 } 3701 3702 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 3703 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier); 3704 } 3705 3706 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 3707 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc()); 3708 } 3709 3710 void CodeGenFunction::EmitOMPTaskgroupDirective( 3711 const OMPTaskgroupDirective &S) { 3712 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3713 Action.Enter(CGF); 3714 if (const Expr *E = S.getReductionRef()) { 3715 SmallVector<const Expr *, 4> LHSs; 3716 SmallVector<const Expr *, 4> RHSs; 3717 OMPTaskDataTy Data; 3718 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) { 3719 auto IPriv = C->privates().begin(); 3720 auto IRed = C->reduction_ops().begin(); 3721 auto ILHS = C->lhs_exprs().begin(); 3722 auto IRHS = C->rhs_exprs().begin(); 3723 for (const Expr *Ref : C->varlists()) { 3724 Data.ReductionVars.emplace_back(Ref); 3725 Data.ReductionCopies.emplace_back(*IPriv); 3726 Data.ReductionOps.emplace_back(*IRed); 3727 LHSs.emplace_back(*ILHS); 3728 RHSs.emplace_back(*IRHS); 3729 std::advance(IPriv, 1); 3730 std::advance(IRed, 1); 3731 std::advance(ILHS, 1); 3732 std::advance(IRHS, 1); 3733 } 3734 } 3735 llvm::Value *ReductionDesc = 3736 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(), 3737 LHSs, RHSs, Data); 3738 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3739 CGF.EmitVarDecl(*VD); 3740 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD), 3741 /*Volatile=*/false, E->getType()); 3742 } 3743 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3744 }; 3745 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3746 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc()); 3747 } 3748 3749 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 3750 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>() 3751 ? llvm::AtomicOrdering::NotAtomic 3752 : llvm::AtomicOrdering::AcquireRelease; 3753 CGM.getOpenMPRuntime().emitFlush( 3754 *this, 3755 [&S]() -> ArrayRef<const Expr *> { 3756 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) 3757 return llvm::makeArrayRef(FlushClause->varlist_begin(), 3758 FlushClause->varlist_end()); 3759 return llvm::None; 3760 }(), 3761 S.getBeginLoc(), AO); 3762 } 3763 3764 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S, 3765 const CodeGenLoopTy &CodeGenLoop, 3766 Expr *IncExpr) { 3767 // Emit the loop iteration variable. 3768 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 3769 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 3770 EmitVarDecl(*IVDecl); 3771 3772 // Emit the iterations count variable. 3773 // If it is not a variable, Sema decided to calculate iterations count on each 3774 // iteration (e.g., it is foldable into a constant). 3775 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 3776 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 3777 // Emit calculation of the iterations count. 3778 EmitIgnoredExpr(S.getCalcLastIteration()); 3779 } 3780 3781 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 3782 3783 bool HasLastprivateClause = false; 3784 // Check pre-condition. 3785 { 3786 OMPLoopScope PreInitScope(*this, S); 3787 // Skip the entire loop if we don't meet the precondition. 3788 // If the condition constant folds and can be elided, avoid emitting the 3789 // whole loop. 3790 bool CondConstant; 3791 llvm::BasicBlock *ContBlock = nullptr; 3792 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 3793 if (!CondConstant) 3794 return; 3795 } else { 3796 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 3797 ContBlock = createBasicBlock("omp.precond.end"); 3798 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 3799 getProfileCount(&S)); 3800 EmitBlock(ThenBlock); 3801 incrementProfileCounter(&S); 3802 } 3803 3804 emitAlignedClause(*this, S); 3805 // Emit 'then' code. 3806 { 3807 // Emit helper vars inits. 3808 3809 LValue LB = EmitOMPHelperVar( 3810 *this, cast<DeclRefExpr>( 3811 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3812 ? S.getCombinedLowerBoundVariable() 3813 : S.getLowerBoundVariable()))); 3814 LValue UB = EmitOMPHelperVar( 3815 *this, cast<DeclRefExpr>( 3816 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3817 ? S.getCombinedUpperBoundVariable() 3818 : S.getUpperBoundVariable()))); 3819 LValue ST = 3820 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 3821 LValue IL = 3822 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 3823 3824 OMPPrivateScope LoopScope(*this); 3825 if (EmitOMPFirstprivateClause(S, LoopScope)) { 3826 // Emit implicit barrier to synchronize threads and avoid data races 3827 // on initialization of firstprivate variables and post-update of 3828 // lastprivate variables. 3829 CGM.getOpenMPRuntime().emitBarrierCall( 3830 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3831 /*ForceSimpleCall=*/true); 3832 } 3833 EmitOMPPrivateClause(S, LoopScope); 3834 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 3835 !isOpenMPParallelDirective(S.getDirectiveKind()) && 3836 !isOpenMPTeamsDirective(S.getDirectiveKind())) 3837 EmitOMPReductionClauseInit(S, LoopScope); 3838 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 3839 EmitOMPPrivateLoopCounters(S, LoopScope); 3840 (void)LoopScope.Privatize(); 3841 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3842 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 3843 3844 // Detect the distribute schedule kind and chunk. 3845 llvm::Value *Chunk = nullptr; 3846 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown; 3847 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) { 3848 ScheduleKind = C->getDistScheduleKind(); 3849 if (const Expr *Ch = C->getChunkSize()) { 3850 Chunk = EmitScalarExpr(Ch); 3851 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 3852 S.getIterationVariable()->getType(), 3853 S.getBeginLoc()); 3854 } 3855 } else { 3856 // Default behaviour for dist_schedule clause. 3857 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk( 3858 *this, S, ScheduleKind, Chunk); 3859 } 3860 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 3861 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 3862 3863 // OpenMP [2.10.8, distribute Construct, Description] 3864 // If dist_schedule is specified, kind must be static. If specified, 3865 // iterations are divided into chunks of size chunk_size, chunks are 3866 // assigned to the teams of the league in a round-robin fashion in the 3867 // order of the team number. When no chunk_size is specified, the 3868 // iteration space is divided into chunks that are approximately equal 3869 // in size, and at most one chunk is distributed to each team of the 3870 // league. The size of the chunks is unspecified in this case. 3871 bool StaticChunked = RT.isStaticChunked( 3872 ScheduleKind, /* Chunked */ Chunk != nullptr) && 3873 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 3874 if (RT.isStaticNonchunked(ScheduleKind, 3875 /* Chunked */ Chunk != nullptr) || 3876 StaticChunked) { 3877 CGOpenMPRuntime::StaticRTInput StaticInit( 3878 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this), 3879 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 3880 StaticChunked ? Chunk : nullptr); 3881 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, 3882 StaticInit); 3883 JumpDest LoopExit = 3884 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 3885 // UB = min(UB, GlobalUB); 3886 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3887 ? S.getCombinedEnsureUpperBound() 3888 : S.getEnsureUpperBound()); 3889 // IV = LB; 3890 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3891 ? S.getCombinedInit() 3892 : S.getInit()); 3893 3894 const Expr *Cond = 3895 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3896 ? S.getCombinedCond() 3897 : S.getCond(); 3898 3899 if (StaticChunked) 3900 Cond = S.getCombinedDistCond(); 3901 3902 // For static unchunked schedules generate: 3903 // 3904 // 1. For distribute alone, codegen 3905 // while (idx <= UB) { 3906 // BODY; 3907 // ++idx; 3908 // } 3909 // 3910 // 2. When combined with 'for' (e.g. as in 'distribute parallel for') 3911 // while (idx <= UB) { 3912 // <CodeGen rest of pragma>(LB, UB); 3913 // idx += ST; 3914 // } 3915 // 3916 // For static chunk one schedule generate: 3917 // 3918 // while (IV <= GlobalUB) { 3919 // <CodeGen rest of pragma>(LB, UB); 3920 // LB += ST; 3921 // UB += ST; 3922 // UB = min(UB, GlobalUB); 3923 // IV = LB; 3924 // } 3925 // 3926 emitCommonSimdLoop( 3927 *this, S, 3928 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3929 if (isOpenMPSimdDirective(S.getDirectiveKind())) 3930 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true); 3931 }, 3932 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop, 3933 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) { 3934 CGF.EmitOMPInnerLoop( 3935 S, LoopScope.requiresCleanups(), Cond, IncExpr, 3936 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 3937 CodeGenLoop(CGF, S, LoopExit); 3938 }, 3939 [&S, StaticChunked](CodeGenFunction &CGF) { 3940 if (StaticChunked) { 3941 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound()); 3942 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound()); 3943 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound()); 3944 CGF.EmitIgnoredExpr(S.getCombinedInit()); 3945 } 3946 }); 3947 }); 3948 EmitBlock(LoopExit.getBlock()); 3949 // Tell the runtime we are done. 3950 RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind()); 3951 } else { 3952 // Emit the outer loop, which requests its work chunk [LB..UB] from 3953 // runtime and runs the inner loop to process it. 3954 const OMPLoopArguments LoopArguments = { 3955 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 3956 IL.getAddress(*this), Chunk}; 3957 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments, 3958 CodeGenLoop); 3959 } 3960 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 3961 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 3962 return CGF.Builder.CreateIsNotNull( 3963 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3964 }); 3965 } 3966 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 3967 !isOpenMPParallelDirective(S.getDirectiveKind()) && 3968 !isOpenMPTeamsDirective(S.getDirectiveKind())) { 3969 EmitOMPReductionClauseFinal(S, OMPD_simd); 3970 // Emit post-update of the reduction variables if IsLastIter != 0. 3971 emitPostUpdateForReductionClause( 3972 *this, S, [IL, &S](CodeGenFunction &CGF) { 3973 return CGF.Builder.CreateIsNotNull( 3974 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3975 }); 3976 } 3977 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3978 if (HasLastprivateClause) { 3979 EmitOMPLastprivateClauseFinal( 3980 S, /*NoFinals=*/false, 3981 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 3982 } 3983 } 3984 3985 // We're now done with the loop, so jump to the continuation block. 3986 if (ContBlock) { 3987 EmitBranch(ContBlock); 3988 EmitBlock(ContBlock, true); 3989 } 3990 } 3991 } 3992 3993 void CodeGenFunction::EmitOMPDistributeDirective( 3994 const OMPDistributeDirective &S) { 3995 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3996 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 3997 }; 3998 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3999 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 4000 } 4001 4002 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM, 4003 const CapturedStmt *S, 4004 SourceLocation Loc) { 4005 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); 4006 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo; 4007 CGF.CapturedStmtInfo = &CapStmtInfo; 4008 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc); 4009 Fn->setDoesNotRecurse(); 4010 return Fn; 4011 } 4012 4013 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 4014 if (S.hasClausesOfKind<OMPDependClause>()) { 4015 assert(!S.getAssociatedStmt() && 4016 "No associated statement must be in ordered depend construct."); 4017 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) 4018 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC); 4019 return; 4020 } 4021 const auto *C = S.getSingleClause<OMPSIMDClause>(); 4022 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF, 4023 PrePostActionTy &Action) { 4024 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 4025 if (C) { 4026 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 4027 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 4028 llvm::Function *OutlinedFn = 4029 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc()); 4030 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(), 4031 OutlinedFn, CapturedVars); 4032 } else { 4033 Action.Enter(CGF); 4034 CGF.EmitStmt(CS->getCapturedStmt()); 4035 } 4036 }; 4037 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4038 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C); 4039 } 4040 4041 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 4042 QualType SrcType, QualType DestType, 4043 SourceLocation Loc) { 4044 assert(CGF.hasScalarEvaluationKind(DestType) && 4045 "DestType must have scalar evaluation kind."); 4046 assert(!Val.isAggregate() && "Must be a scalar or complex."); 4047 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 4048 DestType, Loc) 4049 : CGF.EmitComplexToScalarConversion( 4050 Val.getComplexVal(), SrcType, DestType, Loc); 4051 } 4052 4053 static CodeGenFunction::ComplexPairTy 4054 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 4055 QualType DestType, SourceLocation Loc) { 4056 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 4057 "DestType must have complex evaluation kind."); 4058 CodeGenFunction::ComplexPairTy ComplexVal; 4059 if (Val.isScalar()) { 4060 // Convert the input element to the element type of the complex. 4061 QualType DestElementType = 4062 DestType->castAs<ComplexType>()->getElementType(); 4063 llvm::Value *ScalarVal = CGF.EmitScalarConversion( 4064 Val.getScalarVal(), SrcType, DestElementType, Loc); 4065 ComplexVal = CodeGenFunction::ComplexPairTy( 4066 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 4067 } else { 4068 assert(Val.isComplex() && "Must be a scalar or complex."); 4069 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 4070 QualType DestElementType = 4071 DestType->castAs<ComplexType>()->getElementType(); 4072 ComplexVal.first = CGF.EmitScalarConversion( 4073 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 4074 ComplexVal.second = CGF.EmitScalarConversion( 4075 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 4076 } 4077 return ComplexVal; 4078 } 4079 4080 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 4081 LValue LVal, RValue RVal) { 4082 if (LVal.isGlobalReg()) 4083 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 4084 else 4085 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false); 4086 } 4087 4088 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, 4089 llvm::AtomicOrdering AO, LValue LVal, 4090 SourceLocation Loc) { 4091 if (LVal.isGlobalReg()) 4092 return CGF.EmitLoadOfLValue(LVal, Loc); 4093 return CGF.EmitAtomicLoad( 4094 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO), 4095 LVal.isVolatile()); 4096 } 4097 4098 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal, 4099 QualType RValTy, SourceLocation Loc) { 4100 switch (getEvaluationKind(LVal.getType())) { 4101 case TEK_Scalar: 4102 EmitStoreThroughLValue(RValue::get(convertToScalarValue( 4103 *this, RVal, RValTy, LVal.getType(), Loc)), 4104 LVal); 4105 break; 4106 case TEK_Complex: 4107 EmitStoreOfComplex( 4108 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal, 4109 /*isInit=*/false); 4110 break; 4111 case TEK_Aggregate: 4112 llvm_unreachable("Must be a scalar or complex."); 4113 } 4114 } 4115 4116 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 4117 const Expr *X, const Expr *V, 4118 SourceLocation Loc) { 4119 // v = x; 4120 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 4121 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 4122 LValue XLValue = CGF.EmitLValue(X); 4123 LValue VLValue = CGF.EmitLValue(V); 4124 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc); 4125 // OpenMP, 2.17.7, atomic Construct 4126 // If the read or capture clause is specified and the acquire, acq_rel, or 4127 // seq_cst clause is specified then the strong flush on exit from the atomic 4128 // operation is also an acquire flush. 4129 switch (AO) { 4130 case llvm::AtomicOrdering::Acquire: 4131 case llvm::AtomicOrdering::AcquireRelease: 4132 case llvm::AtomicOrdering::SequentiallyConsistent: 4133 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4134 llvm::AtomicOrdering::Acquire); 4135 break; 4136 case llvm::AtomicOrdering::Monotonic: 4137 case llvm::AtomicOrdering::Release: 4138 break; 4139 case llvm::AtomicOrdering::NotAtomic: 4140 case llvm::AtomicOrdering::Unordered: 4141 llvm_unreachable("Unexpected ordering."); 4142 } 4143 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc); 4144 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 4145 } 4146 4147 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, 4148 llvm::AtomicOrdering AO, const Expr *X, 4149 const Expr *E, SourceLocation Loc) { 4150 // x = expr; 4151 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 4152 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 4153 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4154 // OpenMP, 2.17.7, atomic Construct 4155 // If the write, update, or capture clause is specified and the release, 4156 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4157 // the atomic operation is also a release flush. 4158 switch (AO) { 4159 case llvm::AtomicOrdering::Release: 4160 case llvm::AtomicOrdering::AcquireRelease: 4161 case llvm::AtomicOrdering::SequentiallyConsistent: 4162 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4163 llvm::AtomicOrdering::Release); 4164 break; 4165 case llvm::AtomicOrdering::Acquire: 4166 case llvm::AtomicOrdering::Monotonic: 4167 break; 4168 case llvm::AtomicOrdering::NotAtomic: 4169 case llvm::AtomicOrdering::Unordered: 4170 llvm_unreachable("Unexpected ordering."); 4171 } 4172 } 4173 4174 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 4175 RValue Update, 4176 BinaryOperatorKind BO, 4177 llvm::AtomicOrdering AO, 4178 bool IsXLHSInRHSPart) { 4179 ASTContext &Context = CGF.getContext(); 4180 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 4181 // expression is simple and atomic is allowed for the given type for the 4182 // target platform. 4183 if (BO == BO_Comma || !Update.isScalar() || 4184 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() || 4185 (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 4186 (Update.getScalarVal()->getType() != 4187 X.getAddress(CGF).getElementType())) || 4188 !X.getAddress(CGF).getElementType()->isIntegerTy() || 4189 !Context.getTargetInfo().hasBuiltinAtomic( 4190 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 4191 return std::make_pair(false, RValue::get(nullptr)); 4192 4193 llvm::AtomicRMWInst::BinOp RMWOp; 4194 switch (BO) { 4195 case BO_Add: 4196 RMWOp = llvm::AtomicRMWInst::Add; 4197 break; 4198 case BO_Sub: 4199 if (!IsXLHSInRHSPart) 4200 return std::make_pair(false, RValue::get(nullptr)); 4201 RMWOp = llvm::AtomicRMWInst::Sub; 4202 break; 4203 case BO_And: 4204 RMWOp = llvm::AtomicRMWInst::And; 4205 break; 4206 case BO_Or: 4207 RMWOp = llvm::AtomicRMWInst::Or; 4208 break; 4209 case BO_Xor: 4210 RMWOp = llvm::AtomicRMWInst::Xor; 4211 break; 4212 case BO_LT: 4213 RMWOp = X.getType()->hasSignedIntegerRepresentation() 4214 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 4215 : llvm::AtomicRMWInst::Max) 4216 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 4217 : llvm::AtomicRMWInst::UMax); 4218 break; 4219 case BO_GT: 4220 RMWOp = X.getType()->hasSignedIntegerRepresentation() 4221 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 4222 : llvm::AtomicRMWInst::Min) 4223 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 4224 : llvm::AtomicRMWInst::UMin); 4225 break; 4226 case BO_Assign: 4227 RMWOp = llvm::AtomicRMWInst::Xchg; 4228 break; 4229 case BO_Mul: 4230 case BO_Div: 4231 case BO_Rem: 4232 case BO_Shl: 4233 case BO_Shr: 4234 case BO_LAnd: 4235 case BO_LOr: 4236 return std::make_pair(false, RValue::get(nullptr)); 4237 case BO_PtrMemD: 4238 case BO_PtrMemI: 4239 case BO_LE: 4240 case BO_GE: 4241 case BO_EQ: 4242 case BO_NE: 4243 case BO_Cmp: 4244 case BO_AddAssign: 4245 case BO_SubAssign: 4246 case BO_AndAssign: 4247 case BO_OrAssign: 4248 case BO_XorAssign: 4249 case BO_MulAssign: 4250 case BO_DivAssign: 4251 case BO_RemAssign: 4252 case BO_ShlAssign: 4253 case BO_ShrAssign: 4254 case BO_Comma: 4255 llvm_unreachable("Unsupported atomic update operation"); 4256 } 4257 llvm::Value *UpdateVal = Update.getScalarVal(); 4258 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 4259 UpdateVal = CGF.Builder.CreateIntCast( 4260 IC, X.getAddress(CGF).getElementType(), 4261 X.getType()->hasSignedIntegerRepresentation()); 4262 } 4263 llvm::Value *Res = 4264 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO); 4265 return std::make_pair(true, RValue::get(Res)); 4266 } 4267 4268 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 4269 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 4270 llvm::AtomicOrdering AO, SourceLocation Loc, 4271 const llvm::function_ref<RValue(RValue)> CommonGen) { 4272 // Update expressions are allowed to have the following forms: 4273 // x binop= expr; -> xrval + expr; 4274 // x++, ++x -> xrval + 1; 4275 // x--, --x -> xrval - 1; 4276 // x = x binop expr; -> xrval binop expr 4277 // x = expr Op x; - > expr binop xrval; 4278 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 4279 if (!Res.first) { 4280 if (X.isGlobalReg()) { 4281 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 4282 // 'xrval'. 4283 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 4284 } else { 4285 // Perform compare-and-swap procedure. 4286 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 4287 } 4288 } 4289 return Res; 4290 } 4291 4292 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, 4293 llvm::AtomicOrdering AO, const Expr *X, 4294 const Expr *E, const Expr *UE, 4295 bool IsXLHSInRHSPart, SourceLocation Loc) { 4296 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 4297 "Update expr in 'atomic update' must be a binary operator."); 4298 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 4299 // Update expressions are allowed to have the following forms: 4300 // x binop= expr; -> xrval + expr; 4301 // x++, ++x -> xrval + 1; 4302 // x--, --x -> xrval - 1; 4303 // x = x binop expr; -> xrval binop expr 4304 // x = expr Op x; - > expr binop xrval; 4305 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 4306 LValue XLValue = CGF.EmitLValue(X); 4307 RValue ExprRValue = CGF.EmitAnyExpr(E); 4308 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 4309 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 4310 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 4311 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 4312 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) { 4313 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4314 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 4315 return CGF.EmitAnyExpr(UE); 4316 }; 4317 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 4318 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 4319 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4320 // OpenMP, 2.17.7, atomic Construct 4321 // If the write, update, or capture clause is specified and the release, 4322 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4323 // the atomic operation is also a release flush. 4324 switch (AO) { 4325 case llvm::AtomicOrdering::Release: 4326 case llvm::AtomicOrdering::AcquireRelease: 4327 case llvm::AtomicOrdering::SequentiallyConsistent: 4328 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4329 llvm::AtomicOrdering::Release); 4330 break; 4331 case llvm::AtomicOrdering::Acquire: 4332 case llvm::AtomicOrdering::Monotonic: 4333 break; 4334 case llvm::AtomicOrdering::NotAtomic: 4335 case llvm::AtomicOrdering::Unordered: 4336 llvm_unreachable("Unexpected ordering."); 4337 } 4338 } 4339 4340 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 4341 QualType SourceType, QualType ResType, 4342 SourceLocation Loc) { 4343 switch (CGF.getEvaluationKind(ResType)) { 4344 case TEK_Scalar: 4345 return RValue::get( 4346 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 4347 case TEK_Complex: { 4348 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 4349 return RValue::getComplex(Res.first, Res.second); 4350 } 4351 case TEK_Aggregate: 4352 break; 4353 } 4354 llvm_unreachable("Must be a scalar or complex."); 4355 } 4356 4357 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, 4358 llvm::AtomicOrdering AO, 4359 bool IsPostfixUpdate, const Expr *V, 4360 const Expr *X, const Expr *E, 4361 const Expr *UE, bool IsXLHSInRHSPart, 4362 SourceLocation Loc) { 4363 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 4364 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 4365 RValue NewVVal; 4366 LValue VLValue = CGF.EmitLValue(V); 4367 LValue XLValue = CGF.EmitLValue(X); 4368 RValue ExprRValue = CGF.EmitAnyExpr(E); 4369 QualType NewVValType; 4370 if (UE) { 4371 // 'x' is updated with some additional value. 4372 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 4373 "Update expr in 'atomic capture' must be a binary operator."); 4374 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 4375 // Update expressions are allowed to have the following forms: 4376 // x binop= expr; -> xrval + expr; 4377 // x++, ++x -> xrval + 1; 4378 // x--, --x -> xrval - 1; 4379 // x = x binop expr; -> xrval binop expr 4380 // x = expr Op x; - > expr binop xrval; 4381 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 4382 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 4383 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 4384 NewVValType = XRValExpr->getType(); 4385 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 4386 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 4387 IsPostfixUpdate](RValue XRValue) { 4388 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4389 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 4390 RValue Res = CGF.EmitAnyExpr(UE); 4391 NewVVal = IsPostfixUpdate ? XRValue : Res; 4392 return Res; 4393 }; 4394 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 4395 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 4396 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4397 if (Res.first) { 4398 // 'atomicrmw' instruction was generated. 4399 if (IsPostfixUpdate) { 4400 // Use old value from 'atomicrmw'. 4401 NewVVal = Res.second; 4402 } else { 4403 // 'atomicrmw' does not provide new value, so evaluate it using old 4404 // value of 'x'. 4405 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4406 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 4407 NewVVal = CGF.EmitAnyExpr(UE); 4408 } 4409 } 4410 } else { 4411 // 'x' is simply rewritten with some 'expr'. 4412 NewVValType = X->getType().getNonReferenceType(); 4413 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 4414 X->getType().getNonReferenceType(), Loc); 4415 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) { 4416 NewVVal = XRValue; 4417 return ExprRValue; 4418 }; 4419 // Try to perform atomicrmw xchg, otherwise simple exchange. 4420 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 4421 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 4422 Loc, Gen); 4423 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4424 if (Res.first) { 4425 // 'atomicrmw' instruction was generated. 4426 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 4427 } 4428 } 4429 // Emit post-update store to 'v' of old/new 'x' value. 4430 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc); 4431 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 4432 // OpenMP, 2.17.7, atomic Construct 4433 // If the write, update, or capture clause is specified and the release, 4434 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4435 // the atomic operation is also a release flush. 4436 // If the read or capture clause is specified and the acquire, acq_rel, or 4437 // seq_cst clause is specified then the strong flush on exit from the atomic 4438 // operation is also an acquire flush. 4439 switch (AO) { 4440 case llvm::AtomicOrdering::Release: 4441 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4442 llvm::AtomicOrdering::Release); 4443 break; 4444 case llvm::AtomicOrdering::Acquire: 4445 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4446 llvm::AtomicOrdering::Acquire); 4447 break; 4448 case llvm::AtomicOrdering::AcquireRelease: 4449 case llvm::AtomicOrdering::SequentiallyConsistent: 4450 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4451 llvm::AtomicOrdering::AcquireRelease); 4452 break; 4453 case llvm::AtomicOrdering::Monotonic: 4454 break; 4455 case llvm::AtomicOrdering::NotAtomic: 4456 case llvm::AtomicOrdering::Unordered: 4457 llvm_unreachable("Unexpected ordering."); 4458 } 4459 } 4460 4461 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 4462 llvm::AtomicOrdering AO, bool IsPostfixUpdate, 4463 const Expr *X, const Expr *V, const Expr *E, 4464 const Expr *UE, bool IsXLHSInRHSPart, 4465 SourceLocation Loc) { 4466 switch (Kind) { 4467 case OMPC_read: 4468 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc); 4469 break; 4470 case OMPC_write: 4471 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc); 4472 break; 4473 case OMPC_unknown: 4474 case OMPC_update: 4475 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc); 4476 break; 4477 case OMPC_capture: 4478 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE, 4479 IsXLHSInRHSPart, Loc); 4480 break; 4481 case OMPC_if: 4482 case OMPC_final: 4483 case OMPC_num_threads: 4484 case OMPC_private: 4485 case OMPC_firstprivate: 4486 case OMPC_lastprivate: 4487 case OMPC_reduction: 4488 case OMPC_task_reduction: 4489 case OMPC_in_reduction: 4490 case OMPC_safelen: 4491 case OMPC_simdlen: 4492 case OMPC_allocator: 4493 case OMPC_allocate: 4494 case OMPC_collapse: 4495 case OMPC_default: 4496 case OMPC_seq_cst: 4497 case OMPC_acq_rel: 4498 case OMPC_acquire: 4499 case OMPC_release: 4500 case OMPC_relaxed: 4501 case OMPC_shared: 4502 case OMPC_linear: 4503 case OMPC_aligned: 4504 case OMPC_copyin: 4505 case OMPC_copyprivate: 4506 case OMPC_flush: 4507 case OMPC_proc_bind: 4508 case OMPC_schedule: 4509 case OMPC_ordered: 4510 case OMPC_nowait: 4511 case OMPC_untied: 4512 case OMPC_threadprivate: 4513 case OMPC_depend: 4514 case OMPC_mergeable: 4515 case OMPC_device: 4516 case OMPC_threads: 4517 case OMPC_simd: 4518 case OMPC_map: 4519 case OMPC_num_teams: 4520 case OMPC_thread_limit: 4521 case OMPC_priority: 4522 case OMPC_grainsize: 4523 case OMPC_nogroup: 4524 case OMPC_num_tasks: 4525 case OMPC_hint: 4526 case OMPC_dist_schedule: 4527 case OMPC_defaultmap: 4528 case OMPC_uniform: 4529 case OMPC_to: 4530 case OMPC_from: 4531 case OMPC_use_device_ptr: 4532 case OMPC_is_device_ptr: 4533 case OMPC_unified_address: 4534 case OMPC_unified_shared_memory: 4535 case OMPC_reverse_offload: 4536 case OMPC_dynamic_allocators: 4537 case OMPC_atomic_default_mem_order: 4538 case OMPC_device_type: 4539 case OMPC_match: 4540 case OMPC_nontemporal: 4541 case OMPC_order: 4542 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 4543 } 4544 } 4545 4546 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 4547 llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic; 4548 bool MemOrderingSpecified = false; 4549 if (S.getSingleClause<OMPSeqCstClause>()) { 4550 AO = llvm::AtomicOrdering::SequentiallyConsistent; 4551 MemOrderingSpecified = true; 4552 } else if (S.getSingleClause<OMPAcqRelClause>()) { 4553 AO = llvm::AtomicOrdering::AcquireRelease; 4554 MemOrderingSpecified = true; 4555 } else if (S.getSingleClause<OMPAcquireClause>()) { 4556 AO = llvm::AtomicOrdering::Acquire; 4557 MemOrderingSpecified = true; 4558 } else if (S.getSingleClause<OMPReleaseClause>()) { 4559 AO = llvm::AtomicOrdering::Release; 4560 MemOrderingSpecified = true; 4561 } else if (S.getSingleClause<OMPRelaxedClause>()) { 4562 AO = llvm::AtomicOrdering::Monotonic; 4563 MemOrderingSpecified = true; 4564 } 4565 OpenMPClauseKind Kind = OMPC_unknown; 4566 for (const OMPClause *C : S.clauses()) { 4567 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause, 4568 // if it is first). 4569 if (C->getClauseKind() != OMPC_seq_cst && 4570 C->getClauseKind() != OMPC_acq_rel && 4571 C->getClauseKind() != OMPC_acquire && 4572 C->getClauseKind() != OMPC_release && 4573 C->getClauseKind() != OMPC_relaxed) { 4574 Kind = C->getClauseKind(); 4575 break; 4576 } 4577 } 4578 if (!MemOrderingSpecified) { 4579 llvm::AtomicOrdering DefaultOrder = 4580 CGM.getOpenMPRuntime().getDefaultMemoryOrdering(); 4581 if (DefaultOrder == llvm::AtomicOrdering::Monotonic || 4582 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent || 4583 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease && 4584 Kind == OMPC_capture)) { 4585 AO = DefaultOrder; 4586 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) { 4587 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) { 4588 AO = llvm::AtomicOrdering::Release; 4589 } else if (Kind == OMPC_read) { 4590 assert(Kind == OMPC_read && "Unexpected atomic kind."); 4591 AO = llvm::AtomicOrdering::Acquire; 4592 } 4593 } 4594 } 4595 4596 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers(); 4597 if (const auto *FE = dyn_cast<FullExpr>(CS)) 4598 enterFullExpression(FE); 4599 // Processing for statements under 'atomic capture'. 4600 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) { 4601 for (const Stmt *C : Compound->body()) { 4602 if (const auto *FE = dyn_cast<FullExpr>(C)) 4603 enterFullExpression(FE); 4604 } 4605 } 4606 4607 auto &&CodeGen = [&S, Kind, AO, CS](CodeGenFunction &CGF, 4608 PrePostActionTy &) { 4609 CGF.EmitStopPoint(CS); 4610 emitOMPAtomicExpr(CGF, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(), 4611 S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(), 4612 S.getBeginLoc()); 4613 }; 4614 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4615 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen); 4616 } 4617 4618 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 4619 const OMPExecutableDirective &S, 4620 const RegionCodeGenTy &CodeGen) { 4621 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind())); 4622 CodeGenModule &CGM = CGF.CGM; 4623 4624 // On device emit this construct as inlined code. 4625 if (CGM.getLangOpts().OpenMPIsDevice) { 4626 OMPLexicalScope Scope(CGF, S, OMPD_target); 4627 CGM.getOpenMPRuntime().emitInlinedDirective( 4628 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4629 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 4630 }); 4631 return; 4632 } 4633 4634 auto LPCRegion = 4635 CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S); 4636 llvm::Function *Fn = nullptr; 4637 llvm::Constant *FnID = nullptr; 4638 4639 const Expr *IfCond = nullptr; 4640 // Check for the at most one if clause associated with the target region. 4641 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 4642 if (C->getNameModifier() == OMPD_unknown || 4643 C->getNameModifier() == OMPD_target) { 4644 IfCond = C->getCondition(); 4645 break; 4646 } 4647 } 4648 4649 // Check if we have any device clause associated with the directive. 4650 const Expr *Device = nullptr; 4651 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 4652 Device = C->getDevice(); 4653 4654 // Check if we have an if clause whose conditional always evaluates to false 4655 // or if we do not have any targets specified. If so the target region is not 4656 // an offload entry point. 4657 bool IsOffloadEntry = true; 4658 if (IfCond) { 4659 bool Val; 4660 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val) 4661 IsOffloadEntry = false; 4662 } 4663 if (CGM.getLangOpts().OMPTargetTriples.empty()) 4664 IsOffloadEntry = false; 4665 4666 assert(CGF.CurFuncDecl && "No parent declaration for target region!"); 4667 StringRef ParentName; 4668 // In case we have Ctors/Dtors we use the complete type variant to produce 4669 // the mangling of the device outlined kernel. 4670 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl)) 4671 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete)); 4672 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl)) 4673 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete)); 4674 else 4675 ParentName = 4676 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl))); 4677 4678 // Emit target region as a standalone region. 4679 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID, 4680 IsOffloadEntry, CodeGen); 4681 OMPLexicalScope Scope(CGF, S, OMPD_task); 4682 auto &&SizeEmitter = 4683 [IsOffloadEntry](CodeGenFunction &CGF, 4684 const OMPLoopDirective &D) -> llvm::Value * { 4685 if (IsOffloadEntry) { 4686 OMPLoopScope(CGF, D); 4687 // Emit calculation of the iterations count. 4688 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations()); 4689 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty, 4690 /*isSigned=*/false); 4691 return NumIterations; 4692 } 4693 return nullptr; 4694 }; 4695 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device, 4696 SizeEmitter); 4697 } 4698 4699 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, 4700 PrePostActionTy &Action) { 4701 Action.Enter(CGF); 4702 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4703 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4704 CGF.EmitOMPPrivateClause(S, PrivateScope); 4705 (void)PrivateScope.Privatize(); 4706 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 4707 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 4708 4709 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt()); 4710 } 4711 4712 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 4713 StringRef ParentName, 4714 const OMPTargetDirective &S) { 4715 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4716 emitTargetRegion(CGF, S, Action); 4717 }; 4718 llvm::Function *Fn; 4719 llvm::Constant *Addr; 4720 // Emit target region as a standalone region. 4721 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4722 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4723 assert(Fn && Addr && "Target device function emission failed."); 4724 } 4725 4726 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) { 4727 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4728 emitTargetRegion(CGF, S, Action); 4729 }; 4730 emitCommonOMPTargetDirective(*this, S, CodeGen); 4731 } 4732 4733 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, 4734 const OMPExecutableDirective &S, 4735 OpenMPDirectiveKind InnermostKind, 4736 const RegionCodeGenTy &CodeGen) { 4737 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams); 4738 llvm::Function *OutlinedFn = 4739 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction( 4740 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 4741 4742 const auto *NT = S.getSingleClause<OMPNumTeamsClause>(); 4743 const auto *TL = S.getSingleClause<OMPThreadLimitClause>(); 4744 if (NT || TL) { 4745 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr; 4746 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr; 4747 4748 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit, 4749 S.getBeginLoc()); 4750 } 4751 4752 OMPTeamsScope Scope(CGF, S); 4753 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 4754 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 4755 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn, 4756 CapturedVars); 4757 } 4758 4759 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) { 4760 // Emit teams region as a standalone region. 4761 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4762 Action.Enter(CGF); 4763 OMPPrivateScope PrivateScope(CGF); 4764 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4765 CGF.EmitOMPPrivateClause(S, PrivateScope); 4766 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4767 (void)PrivateScope.Privatize(); 4768 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt()); 4769 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4770 }; 4771 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 4772 emitPostUpdateForReductionClause(*this, S, 4773 [](CodeGenFunction &) { return nullptr; }); 4774 } 4775 4776 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 4777 const OMPTargetTeamsDirective &S) { 4778 auto *CS = S.getCapturedStmt(OMPD_teams); 4779 Action.Enter(CGF); 4780 // Emit teams region as a standalone region. 4781 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 4782 Action.Enter(CGF); 4783 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4784 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4785 CGF.EmitOMPPrivateClause(S, PrivateScope); 4786 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4787 (void)PrivateScope.Privatize(); 4788 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 4789 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 4790 CGF.EmitStmt(CS->getCapturedStmt()); 4791 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4792 }; 4793 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen); 4794 emitPostUpdateForReductionClause(CGF, S, 4795 [](CodeGenFunction &) { return nullptr; }); 4796 } 4797 4798 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 4799 CodeGenModule &CGM, StringRef ParentName, 4800 const OMPTargetTeamsDirective &S) { 4801 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4802 emitTargetTeamsRegion(CGF, Action, S); 4803 }; 4804 llvm::Function *Fn; 4805 llvm::Constant *Addr; 4806 // Emit target region as a standalone region. 4807 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4808 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4809 assert(Fn && Addr && "Target device function emission failed."); 4810 } 4811 4812 void CodeGenFunction::EmitOMPTargetTeamsDirective( 4813 const OMPTargetTeamsDirective &S) { 4814 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4815 emitTargetTeamsRegion(CGF, Action, S); 4816 }; 4817 emitCommonOMPTargetDirective(*this, S, CodeGen); 4818 } 4819 4820 static void 4821 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 4822 const OMPTargetTeamsDistributeDirective &S) { 4823 Action.Enter(CGF); 4824 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4825 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4826 }; 4827 4828 // Emit teams region as a standalone region. 4829 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4830 PrePostActionTy &Action) { 4831 Action.Enter(CGF); 4832 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4833 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4834 (void)PrivateScope.Privatize(); 4835 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4836 CodeGenDistribute); 4837 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4838 }; 4839 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen); 4840 emitPostUpdateForReductionClause(CGF, S, 4841 [](CodeGenFunction &) { return nullptr; }); 4842 } 4843 4844 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 4845 CodeGenModule &CGM, StringRef ParentName, 4846 const OMPTargetTeamsDistributeDirective &S) { 4847 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4848 emitTargetTeamsDistributeRegion(CGF, Action, S); 4849 }; 4850 llvm::Function *Fn; 4851 llvm::Constant *Addr; 4852 // Emit target region as a standalone region. 4853 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4854 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4855 assert(Fn && Addr && "Target device function emission failed."); 4856 } 4857 4858 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective( 4859 const OMPTargetTeamsDistributeDirective &S) { 4860 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4861 emitTargetTeamsDistributeRegion(CGF, Action, S); 4862 }; 4863 emitCommonOMPTargetDirective(*this, S, CodeGen); 4864 } 4865 4866 static void emitTargetTeamsDistributeSimdRegion( 4867 CodeGenFunction &CGF, PrePostActionTy &Action, 4868 const OMPTargetTeamsDistributeSimdDirective &S) { 4869 Action.Enter(CGF); 4870 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4871 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4872 }; 4873 4874 // Emit teams region as a standalone region. 4875 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4876 PrePostActionTy &Action) { 4877 Action.Enter(CGF); 4878 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4879 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4880 (void)PrivateScope.Privatize(); 4881 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4882 CodeGenDistribute); 4883 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4884 }; 4885 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen); 4886 emitPostUpdateForReductionClause(CGF, S, 4887 [](CodeGenFunction &) { return nullptr; }); 4888 } 4889 4890 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 4891 CodeGenModule &CGM, StringRef ParentName, 4892 const OMPTargetTeamsDistributeSimdDirective &S) { 4893 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4894 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 4895 }; 4896 llvm::Function *Fn; 4897 llvm::Constant *Addr; 4898 // Emit target region as a standalone region. 4899 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4900 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4901 assert(Fn && Addr && "Target device function emission failed."); 4902 } 4903 4904 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective( 4905 const OMPTargetTeamsDistributeSimdDirective &S) { 4906 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4907 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 4908 }; 4909 emitCommonOMPTargetDirective(*this, S, CodeGen); 4910 } 4911 4912 void CodeGenFunction::EmitOMPTeamsDistributeDirective( 4913 const OMPTeamsDistributeDirective &S) { 4914 4915 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4916 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4917 }; 4918 4919 // Emit teams region as a standalone region. 4920 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4921 PrePostActionTy &Action) { 4922 Action.Enter(CGF); 4923 OMPPrivateScope PrivateScope(CGF); 4924 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4925 (void)PrivateScope.Privatize(); 4926 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4927 CodeGenDistribute); 4928 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4929 }; 4930 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 4931 emitPostUpdateForReductionClause(*this, S, 4932 [](CodeGenFunction &) { return nullptr; }); 4933 } 4934 4935 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective( 4936 const OMPTeamsDistributeSimdDirective &S) { 4937 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4938 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4939 }; 4940 4941 // Emit teams region as a standalone region. 4942 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4943 PrePostActionTy &Action) { 4944 Action.Enter(CGF); 4945 OMPPrivateScope PrivateScope(CGF); 4946 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4947 (void)PrivateScope.Privatize(); 4948 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd, 4949 CodeGenDistribute); 4950 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4951 }; 4952 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen); 4953 emitPostUpdateForReductionClause(*this, S, 4954 [](CodeGenFunction &) { return nullptr; }); 4955 } 4956 4957 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective( 4958 const OMPTeamsDistributeParallelForDirective &S) { 4959 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4960 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 4961 S.getDistInc()); 4962 }; 4963 4964 // Emit teams region as a standalone region. 4965 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4966 PrePostActionTy &Action) { 4967 Action.Enter(CGF); 4968 OMPPrivateScope PrivateScope(CGF); 4969 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4970 (void)PrivateScope.Privatize(); 4971 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4972 CodeGenDistribute); 4973 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4974 }; 4975 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen); 4976 emitPostUpdateForReductionClause(*this, S, 4977 [](CodeGenFunction &) { return nullptr; }); 4978 } 4979 4980 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective( 4981 const OMPTeamsDistributeParallelForSimdDirective &S) { 4982 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4983 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 4984 S.getDistInc()); 4985 }; 4986 4987 // Emit teams region as a standalone region. 4988 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4989 PrePostActionTy &Action) { 4990 Action.Enter(CGF); 4991 OMPPrivateScope PrivateScope(CGF); 4992 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4993 (void)PrivateScope.Privatize(); 4994 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 4995 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 4996 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4997 }; 4998 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd, 4999 CodeGen); 5000 emitPostUpdateForReductionClause(*this, S, 5001 [](CodeGenFunction &) { return nullptr; }); 5002 } 5003 5004 static void emitTargetTeamsDistributeParallelForRegion( 5005 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, 5006 PrePostActionTy &Action) { 5007 Action.Enter(CGF); 5008 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5009 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5010 S.getDistInc()); 5011 }; 5012 5013 // Emit teams region as a standalone region. 5014 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5015 PrePostActionTy &Action) { 5016 Action.Enter(CGF); 5017 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5018 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5019 (void)PrivateScope.Privatize(); 5020 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5021 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5022 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5023 }; 5024 5025 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for, 5026 CodeGenTeams); 5027 emitPostUpdateForReductionClause(CGF, S, 5028 [](CodeGenFunction &) { return nullptr; }); 5029 } 5030 5031 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 5032 CodeGenModule &CGM, StringRef ParentName, 5033 const OMPTargetTeamsDistributeParallelForDirective &S) { 5034 // Emit SPMD target teams distribute parallel for region as a standalone 5035 // region. 5036 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5037 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 5038 }; 5039 llvm::Function *Fn; 5040 llvm::Constant *Addr; 5041 // Emit target region as a standalone region. 5042 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5043 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5044 assert(Fn && Addr && "Target device function emission failed."); 5045 } 5046 5047 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective( 5048 const OMPTargetTeamsDistributeParallelForDirective &S) { 5049 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5050 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 5051 }; 5052 emitCommonOMPTargetDirective(*this, S, CodeGen); 5053 } 5054 5055 static void emitTargetTeamsDistributeParallelForSimdRegion( 5056 CodeGenFunction &CGF, 5057 const OMPTargetTeamsDistributeParallelForSimdDirective &S, 5058 PrePostActionTy &Action) { 5059 Action.Enter(CGF); 5060 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5061 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5062 S.getDistInc()); 5063 }; 5064 5065 // Emit teams region as a standalone region. 5066 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5067 PrePostActionTy &Action) { 5068 Action.Enter(CGF); 5069 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5070 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5071 (void)PrivateScope.Privatize(); 5072 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5073 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5074 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5075 }; 5076 5077 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd, 5078 CodeGenTeams); 5079 emitPostUpdateForReductionClause(CGF, S, 5080 [](CodeGenFunction &) { return nullptr; }); 5081 } 5082 5083 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 5084 CodeGenModule &CGM, StringRef ParentName, 5085 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 5086 // Emit SPMD target teams distribute parallel for simd region as a standalone 5087 // region. 5088 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5089 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 5090 }; 5091 llvm::Function *Fn; 5092 llvm::Constant *Addr; 5093 // Emit target region as a standalone region. 5094 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5095 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5096 assert(Fn && Addr && "Target device function emission failed."); 5097 } 5098 5099 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective( 5100 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 5101 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5102 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 5103 }; 5104 emitCommonOMPTargetDirective(*this, S, CodeGen); 5105 } 5106 5107 void CodeGenFunction::EmitOMPCancellationPointDirective( 5108 const OMPCancellationPointDirective &S) { 5109 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(), 5110 S.getCancelRegion()); 5111 } 5112 5113 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 5114 const Expr *IfCond = nullptr; 5115 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5116 if (C->getNameModifier() == OMPD_unknown || 5117 C->getNameModifier() == OMPD_cancel) { 5118 IfCond = C->getCondition(); 5119 break; 5120 } 5121 } 5122 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 5123 // TODO: This check is necessary as we only generate `omp parallel` through 5124 // the OpenMPIRBuilder for now. 5125 if (S.getCancelRegion() == OMPD_parallel) { 5126 llvm::Value *IfCondition = nullptr; 5127 if (IfCond) 5128 IfCondition = EmitScalarExpr(IfCond, 5129 /*IgnoreResultAssign=*/true); 5130 return Builder.restoreIP( 5131 OMPBuilder->CreateCancel(Builder, IfCondition, S.getCancelRegion())); 5132 } 5133 } 5134 5135 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond, 5136 S.getCancelRegion()); 5137 } 5138 5139 CodeGenFunction::JumpDest 5140 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 5141 if (Kind == OMPD_parallel || Kind == OMPD_task || 5142 Kind == OMPD_target_parallel || Kind == OMPD_taskloop || 5143 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop) 5144 return ReturnBlock; 5145 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections || 5146 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for || 5147 Kind == OMPD_distribute_parallel_for || 5148 Kind == OMPD_target_parallel_for || 5149 Kind == OMPD_teams_distribute_parallel_for || 5150 Kind == OMPD_target_teams_distribute_parallel_for); 5151 return OMPCancelStack.getExitBlock(); 5152 } 5153 5154 void CodeGenFunction::EmitOMPUseDevicePtrClause( 5155 const OMPClause &NC, OMPPrivateScope &PrivateScope, 5156 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 5157 const auto &C = cast<OMPUseDevicePtrClause>(NC); 5158 auto OrigVarIt = C.varlist_begin(); 5159 auto InitIt = C.inits().begin(); 5160 for (const Expr *PvtVarIt : C.private_copies()) { 5161 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl()); 5162 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl()); 5163 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl()); 5164 5165 // In order to identify the right initializer we need to match the 5166 // declaration used by the mapping logic. In some cases we may get 5167 // OMPCapturedExprDecl that refers to the original declaration. 5168 const ValueDecl *MatchingVD = OrigVD; 5169 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 5170 // OMPCapturedExprDecl are used to privative fields of the current 5171 // structure. 5172 const auto *ME = cast<MemberExpr>(OED->getInit()); 5173 assert(isa<CXXThisExpr>(ME->getBase()) && 5174 "Base should be the current struct!"); 5175 MatchingVD = ME->getMemberDecl(); 5176 } 5177 5178 // If we don't have information about the current list item, move on to 5179 // the next one. 5180 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 5181 if (InitAddrIt == CaptureDeviceAddrMap.end()) 5182 continue; 5183 5184 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD, 5185 InitAddrIt, InitVD, 5186 PvtVD]() { 5187 // Initialize the temporary initialization variable with the address we 5188 // get from the runtime library. We have to cast the source address 5189 // because it is always a void *. References are materialized in the 5190 // privatization scope, so the initialization here disregards the fact 5191 // the original variable is a reference. 5192 QualType AddrQTy = 5193 getContext().getPointerType(OrigVD->getType().getNonReferenceType()); 5194 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy); 5195 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy); 5196 setAddrOfLocalVar(InitVD, InitAddr); 5197 5198 // Emit private declaration, it will be initialized by the value we 5199 // declaration we just added to the local declarations map. 5200 EmitDecl(*PvtVD); 5201 5202 // The initialization variables reached its purpose in the emission 5203 // of the previous declaration, so we don't need it anymore. 5204 LocalDeclMap.erase(InitVD); 5205 5206 // Return the address of the private variable. 5207 return GetAddrOfLocalVar(PvtVD); 5208 }); 5209 assert(IsRegistered && "firstprivate var already registered as private"); 5210 // Silence the warning about unused variable. 5211 (void)IsRegistered; 5212 5213 ++OrigVarIt; 5214 ++InitIt; 5215 } 5216 } 5217 5218 // Generate the instructions for '#pragma omp target data' directive. 5219 void CodeGenFunction::EmitOMPTargetDataDirective( 5220 const OMPTargetDataDirective &S) { 5221 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true); 5222 5223 // Create a pre/post action to signal the privatization of the device pointer. 5224 // This action can be replaced by the OpenMP runtime code generation to 5225 // deactivate privatization. 5226 bool PrivatizeDevicePointers = false; 5227 class DevicePointerPrivActionTy : public PrePostActionTy { 5228 bool &PrivatizeDevicePointers; 5229 5230 public: 5231 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers) 5232 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {} 5233 void Enter(CodeGenFunction &CGF) override { 5234 PrivatizeDevicePointers = true; 5235 } 5236 }; 5237 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers); 5238 5239 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers]( 5240 CodeGenFunction &CGF, PrePostActionTy &Action) { 5241 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5242 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 5243 }; 5244 5245 // Codegen that selects whether to generate the privatization code or not. 5246 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers, 5247 &InnermostCodeGen](CodeGenFunction &CGF, 5248 PrePostActionTy &Action) { 5249 RegionCodeGenTy RCG(InnermostCodeGen); 5250 PrivatizeDevicePointers = false; 5251 5252 // Call the pre-action to change the status of PrivatizeDevicePointers if 5253 // needed. 5254 Action.Enter(CGF); 5255 5256 if (PrivatizeDevicePointers) { 5257 OMPPrivateScope PrivateScope(CGF); 5258 // Emit all instances of the use_device_ptr clause. 5259 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>()) 5260 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope, 5261 Info.CaptureDeviceAddrMap); 5262 (void)PrivateScope.Privatize(); 5263 RCG(CGF); 5264 } else { 5265 RCG(CGF); 5266 } 5267 }; 5268 5269 // Forward the provided action to the privatization codegen. 5270 RegionCodeGenTy PrivRCG(PrivCodeGen); 5271 PrivRCG.setAction(Action); 5272 5273 // Notwithstanding the body of the region is emitted as inlined directive, 5274 // we don't use an inline scope as changes in the references inside the 5275 // region are expected to be visible outside, so we do not privative them. 5276 OMPLexicalScope Scope(CGF, S); 5277 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, 5278 PrivRCG); 5279 }; 5280 5281 RegionCodeGenTy RCG(CodeGen); 5282 5283 // If we don't have target devices, don't bother emitting the data mapping 5284 // code. 5285 if (CGM.getLangOpts().OMPTargetTriples.empty()) { 5286 RCG(*this); 5287 return; 5288 } 5289 5290 // Check if we have any if clause associated with the directive. 5291 const Expr *IfCond = nullptr; 5292 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5293 IfCond = C->getCondition(); 5294 5295 // Check if we have any device clause associated with the directive. 5296 const Expr *Device = nullptr; 5297 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5298 Device = C->getDevice(); 5299 5300 // Set the action to signal privatization of device pointers. 5301 RCG.setAction(PrivAction); 5302 5303 // Emit region code. 5304 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG, 5305 Info); 5306 } 5307 5308 void CodeGenFunction::EmitOMPTargetEnterDataDirective( 5309 const OMPTargetEnterDataDirective &S) { 5310 // If we don't have target devices, don't bother emitting the data mapping 5311 // code. 5312 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5313 return; 5314 5315 // Check if we have any if clause associated with the directive. 5316 const Expr *IfCond = nullptr; 5317 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5318 IfCond = C->getCondition(); 5319 5320 // Check if we have any device clause associated with the directive. 5321 const Expr *Device = nullptr; 5322 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5323 Device = C->getDevice(); 5324 5325 OMPLexicalScope Scope(*this, S, OMPD_task); 5326 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5327 } 5328 5329 void CodeGenFunction::EmitOMPTargetExitDataDirective( 5330 const OMPTargetExitDataDirective &S) { 5331 // If we don't have target devices, don't bother emitting the data mapping 5332 // code. 5333 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5334 return; 5335 5336 // Check if we have any if clause associated with the directive. 5337 const Expr *IfCond = nullptr; 5338 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5339 IfCond = C->getCondition(); 5340 5341 // Check if we have any device clause associated with the directive. 5342 const Expr *Device = nullptr; 5343 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5344 Device = C->getDevice(); 5345 5346 OMPLexicalScope Scope(*this, S, OMPD_task); 5347 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5348 } 5349 5350 static void emitTargetParallelRegion(CodeGenFunction &CGF, 5351 const OMPTargetParallelDirective &S, 5352 PrePostActionTy &Action) { 5353 // Get the captured statement associated with the 'parallel' region. 5354 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 5355 Action.Enter(CGF); 5356 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 5357 Action.Enter(CGF); 5358 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5359 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 5360 CGF.EmitOMPPrivateClause(S, PrivateScope); 5361 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5362 (void)PrivateScope.Privatize(); 5363 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 5364 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 5365 // TODO: Add support for clauses. 5366 CGF.EmitStmt(CS->getCapturedStmt()); 5367 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 5368 }; 5369 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen, 5370 emitEmptyBoundParameters); 5371 emitPostUpdateForReductionClause(CGF, S, 5372 [](CodeGenFunction &) { return nullptr; }); 5373 } 5374 5375 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 5376 CodeGenModule &CGM, StringRef ParentName, 5377 const OMPTargetParallelDirective &S) { 5378 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5379 emitTargetParallelRegion(CGF, S, Action); 5380 }; 5381 llvm::Function *Fn; 5382 llvm::Constant *Addr; 5383 // Emit target region as a standalone region. 5384 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5385 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5386 assert(Fn && Addr && "Target device function emission failed."); 5387 } 5388 5389 void CodeGenFunction::EmitOMPTargetParallelDirective( 5390 const OMPTargetParallelDirective &S) { 5391 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5392 emitTargetParallelRegion(CGF, S, Action); 5393 }; 5394 emitCommonOMPTargetDirective(*this, S, CodeGen); 5395 } 5396 5397 static void emitTargetParallelForRegion(CodeGenFunction &CGF, 5398 const OMPTargetParallelForDirective &S, 5399 PrePostActionTy &Action) { 5400 Action.Enter(CGF); 5401 // Emit directive as a combined directive that consists of two implicit 5402 // directives: 'parallel' with 'for' directive. 5403 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5404 Action.Enter(CGF); 5405 CodeGenFunction::OMPCancelStackRAII CancelRegion( 5406 CGF, OMPD_target_parallel_for, S.hasCancel()); 5407 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 5408 emitDispatchForLoopBounds); 5409 }; 5410 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen, 5411 emitEmptyBoundParameters); 5412 } 5413 5414 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 5415 CodeGenModule &CGM, StringRef ParentName, 5416 const OMPTargetParallelForDirective &S) { 5417 // Emit SPMD target parallel for region as a standalone region. 5418 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5419 emitTargetParallelForRegion(CGF, S, Action); 5420 }; 5421 llvm::Function *Fn; 5422 llvm::Constant *Addr; 5423 // Emit target region as a standalone region. 5424 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5425 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5426 assert(Fn && Addr && "Target device function emission failed."); 5427 } 5428 5429 void CodeGenFunction::EmitOMPTargetParallelForDirective( 5430 const OMPTargetParallelForDirective &S) { 5431 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5432 emitTargetParallelForRegion(CGF, S, Action); 5433 }; 5434 emitCommonOMPTargetDirective(*this, S, CodeGen); 5435 } 5436 5437 static void 5438 emitTargetParallelForSimdRegion(CodeGenFunction &CGF, 5439 const OMPTargetParallelForSimdDirective &S, 5440 PrePostActionTy &Action) { 5441 Action.Enter(CGF); 5442 // Emit directive as a combined directive that consists of two implicit 5443 // directives: 'parallel' with 'for' directive. 5444 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5445 Action.Enter(CGF); 5446 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 5447 emitDispatchForLoopBounds); 5448 }; 5449 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen, 5450 emitEmptyBoundParameters); 5451 } 5452 5453 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 5454 CodeGenModule &CGM, StringRef ParentName, 5455 const OMPTargetParallelForSimdDirective &S) { 5456 // Emit SPMD target parallel for region as a standalone region. 5457 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5458 emitTargetParallelForSimdRegion(CGF, S, Action); 5459 }; 5460 llvm::Function *Fn; 5461 llvm::Constant *Addr; 5462 // Emit target region as a standalone region. 5463 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5464 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5465 assert(Fn && Addr && "Target device function emission failed."); 5466 } 5467 5468 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective( 5469 const OMPTargetParallelForSimdDirective &S) { 5470 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5471 emitTargetParallelForSimdRegion(CGF, S, Action); 5472 }; 5473 emitCommonOMPTargetDirective(*this, S, CodeGen); 5474 } 5475 5476 /// Emit a helper variable and return corresponding lvalue. 5477 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, 5478 const ImplicitParamDecl *PVD, 5479 CodeGenFunction::OMPPrivateScope &Privates) { 5480 const auto *VDecl = cast<VarDecl>(Helper->getDecl()); 5481 Privates.addPrivate(VDecl, 5482 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); }); 5483 } 5484 5485 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) { 5486 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind())); 5487 // Emit outlined function for task construct. 5488 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop); 5489 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 5490 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 5491 const Expr *IfCond = nullptr; 5492 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5493 if (C->getNameModifier() == OMPD_unknown || 5494 C->getNameModifier() == OMPD_taskloop) { 5495 IfCond = C->getCondition(); 5496 break; 5497 } 5498 } 5499 5500 OMPTaskDataTy Data; 5501 // Check if taskloop must be emitted without taskgroup. 5502 Data.Nogroup = S.getSingleClause<OMPNogroupClause>(); 5503 // TODO: Check if we should emit tied or untied task. 5504 Data.Tied = true; 5505 // Set scheduling for taskloop 5506 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) { 5507 // grainsize clause 5508 Data.Schedule.setInt(/*IntVal=*/false); 5509 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize())); 5510 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) { 5511 // num_tasks clause 5512 Data.Schedule.setInt(/*IntVal=*/true); 5513 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks())); 5514 } 5515 5516 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) { 5517 // if (PreCond) { 5518 // for (IV in 0..LastIteration) BODY; 5519 // <Final counter/linear vars updates>; 5520 // } 5521 // 5522 5523 // Emit: if (PreCond) - begin. 5524 // If the condition constant folds and can be elided, avoid emitting the 5525 // whole loop. 5526 bool CondConstant; 5527 llvm::BasicBlock *ContBlock = nullptr; 5528 OMPLoopScope PreInitScope(CGF, S); 5529 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 5530 if (!CondConstant) 5531 return; 5532 } else { 5533 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then"); 5534 ContBlock = CGF.createBasicBlock("taskloop.if.end"); 5535 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 5536 CGF.getProfileCount(&S)); 5537 CGF.EmitBlock(ThenBlock); 5538 CGF.incrementProfileCounter(&S); 5539 } 5540 5541 (void)CGF.EmitOMPLinearClauseInit(S); 5542 5543 OMPPrivateScope LoopScope(CGF); 5544 // Emit helper vars inits. 5545 enum { LowerBound = 5, UpperBound, Stride, LastIter }; 5546 auto *I = CS->getCapturedDecl()->param_begin(); 5547 auto *LBP = std::next(I, LowerBound); 5548 auto *UBP = std::next(I, UpperBound); 5549 auto *STP = std::next(I, Stride); 5550 auto *LIP = std::next(I, LastIter); 5551 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP, 5552 LoopScope); 5553 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP, 5554 LoopScope); 5555 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope); 5556 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP, 5557 LoopScope); 5558 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 5559 CGF.EmitOMPLinearClause(S, LoopScope); 5560 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 5561 (void)LoopScope.Privatize(); 5562 // Emit the loop iteration variable. 5563 const Expr *IVExpr = S.getIterationVariable(); 5564 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 5565 CGF.EmitVarDecl(*IVDecl); 5566 CGF.EmitIgnoredExpr(S.getInit()); 5567 5568 // Emit the iterations count variable. 5569 // If it is not a variable, Sema decided to calculate iterations count on 5570 // each iteration (e.g., it is foldable into a constant). 5571 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 5572 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 5573 // Emit calculation of the iterations count. 5574 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 5575 } 5576 5577 { 5578 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 5579 emitCommonSimdLoop( 5580 CGF, S, 5581 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5582 if (isOpenMPSimdDirective(S.getDirectiveKind())) 5583 CGF.EmitOMPSimdInit(S); 5584 }, 5585 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 5586 CGF.EmitOMPInnerLoop( 5587 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 5588 [&S](CodeGenFunction &CGF) { 5589 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest()); 5590 CGF.EmitStopPoint(&S); 5591 }, 5592 [](CodeGenFunction &) {}); 5593 }); 5594 } 5595 // Emit: if (PreCond) - end. 5596 if (ContBlock) { 5597 CGF.EmitBranch(ContBlock); 5598 CGF.EmitBlock(ContBlock, true); 5599 } 5600 // Emit final copy of the lastprivate variables if IsLastIter != 0. 5601 if (HasLastprivateClause) { 5602 CGF.EmitOMPLastprivateClauseFinal( 5603 S, isOpenMPSimdDirective(S.getDirectiveKind()), 5604 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar( 5605 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 5606 (*LIP)->getType(), S.getBeginLoc()))); 5607 } 5608 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) { 5609 return CGF.Builder.CreateIsNotNull( 5610 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 5611 (*LIP)->getType(), S.getBeginLoc())); 5612 }); 5613 }; 5614 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 5615 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 5616 const OMPTaskDataTy &Data) { 5617 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond, 5618 &Data](CodeGenFunction &CGF, PrePostActionTy &) { 5619 OMPLoopScope PreInitScope(CGF, S); 5620 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S, 5621 OutlinedFn, SharedsTy, 5622 CapturedStruct, IfCond, Data); 5623 }; 5624 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop, 5625 CodeGen); 5626 }; 5627 if (Data.Nogroup) { 5628 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data); 5629 } else { 5630 CGM.getOpenMPRuntime().emitTaskgroupRegion( 5631 *this, 5632 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF, 5633 PrePostActionTy &Action) { 5634 Action.Enter(CGF); 5635 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, 5636 Data); 5637 }, 5638 S.getBeginLoc()); 5639 } 5640 } 5641 5642 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) { 5643 auto LPCRegion = 5644 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5645 EmitOMPTaskLoopBasedDirective(S); 5646 } 5647 5648 void CodeGenFunction::EmitOMPTaskLoopSimdDirective( 5649 const OMPTaskLoopSimdDirective &S) { 5650 auto LPCRegion = 5651 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5652 OMPLexicalScope Scope(*this, S); 5653 EmitOMPTaskLoopBasedDirective(S); 5654 } 5655 5656 void CodeGenFunction::EmitOMPMasterTaskLoopDirective( 5657 const OMPMasterTaskLoopDirective &S) { 5658 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5659 Action.Enter(CGF); 5660 EmitOMPTaskLoopBasedDirective(S); 5661 }; 5662 auto LPCRegion = 5663 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5664 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false); 5665 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 5666 } 5667 5668 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective( 5669 const OMPMasterTaskLoopSimdDirective &S) { 5670 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5671 Action.Enter(CGF); 5672 EmitOMPTaskLoopBasedDirective(S); 5673 }; 5674 auto LPCRegion = 5675 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5676 OMPLexicalScope Scope(*this, S); 5677 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 5678 } 5679 5680 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective( 5681 const OMPParallelMasterTaskLoopDirective &S) { 5682 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5683 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 5684 PrePostActionTy &Action) { 5685 Action.Enter(CGF); 5686 CGF.EmitOMPTaskLoopBasedDirective(S); 5687 }; 5688 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 5689 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 5690 S.getBeginLoc()); 5691 }; 5692 auto LPCRegion = 5693 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5694 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen, 5695 emitEmptyBoundParameters); 5696 } 5697 5698 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective( 5699 const OMPParallelMasterTaskLoopSimdDirective &S) { 5700 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5701 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 5702 PrePostActionTy &Action) { 5703 Action.Enter(CGF); 5704 CGF.EmitOMPTaskLoopBasedDirective(S); 5705 }; 5706 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 5707 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 5708 S.getBeginLoc()); 5709 }; 5710 auto LPCRegion = 5711 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5712 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen, 5713 emitEmptyBoundParameters); 5714 } 5715 5716 // Generate the instructions for '#pragma omp target update' directive. 5717 void CodeGenFunction::EmitOMPTargetUpdateDirective( 5718 const OMPTargetUpdateDirective &S) { 5719 // If we don't have target devices, don't bother emitting the data mapping 5720 // code. 5721 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5722 return; 5723 5724 // Check if we have any if clause associated with the directive. 5725 const Expr *IfCond = nullptr; 5726 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5727 IfCond = C->getCondition(); 5728 5729 // Check if we have any device clause associated with the directive. 5730 const Expr *Device = nullptr; 5731 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5732 Device = C->getDevice(); 5733 5734 OMPLexicalScope Scope(*this, S, OMPD_task); 5735 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5736 } 5737 5738 void CodeGenFunction::EmitSimpleOMPExecutableDirective( 5739 const OMPExecutableDirective &D) { 5740 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt()) 5741 return; 5742 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) { 5743 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 5744 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action); 5745 } else { 5746 OMPPrivateScope LoopGlobals(CGF); 5747 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) { 5748 for (const Expr *E : LD->counters()) { 5749 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 5750 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) { 5751 LValue GlobLVal = CGF.EmitLValue(E); 5752 LoopGlobals.addPrivate( 5753 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 5754 } 5755 if (isa<OMPCapturedExprDecl>(VD)) { 5756 // Emit only those that were not explicitly referenced in clauses. 5757 if (!CGF.LocalDeclMap.count(VD)) 5758 CGF.EmitVarDecl(*VD); 5759 } 5760 } 5761 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) { 5762 if (!C->getNumForLoops()) 5763 continue; 5764 for (unsigned I = LD->getCollapsedNumber(), 5765 E = C->getLoopNumIterations().size(); 5766 I < E; ++I) { 5767 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>( 5768 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) { 5769 // Emit only those that were not explicitly referenced in clauses. 5770 if (!CGF.LocalDeclMap.count(VD)) 5771 CGF.EmitVarDecl(*VD); 5772 } 5773 } 5774 } 5775 } 5776 LoopGlobals.Privatize(); 5777 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt()); 5778 } 5779 }; 5780 { 5781 auto LPCRegion = 5782 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D); 5783 OMPSimdLexicalScope Scope(*this, D); 5784 CGM.getOpenMPRuntime().emitInlinedDirective( 5785 *this, 5786 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd 5787 : D.getDirectiveKind(), 5788 CodeGen); 5789 } 5790 // Check for outer lastprivate conditional update. 5791 checkForLastprivateConditionalUpdate(*this, D); 5792 } 5793