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