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 const 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 = BinaryOperator::Create( 2934 C, &IVRefExpr, &UBRefExpr, BO_LE, C.BoolTy, VK_RValue, OK_Ordinary, 2935 S.getBeginLoc(), FPOptions(C.getLangOpts())); 2936 // Increment for loop counter. 2937 UnaryOperator Inc(&IVRefExpr, UO_PreInc, KmpInt32Ty, VK_RValue, OK_Ordinary, 2938 S.getBeginLoc(), true); 2939 auto &&BodyGen = [CapturedStmt, CS, &S, &IV](CodeGenFunction &CGF) { 2940 // Iterate through all sections and emit a switch construct: 2941 // switch (IV) { 2942 // case 0: 2943 // <SectionStmt[0]>; 2944 // break; 2945 // ... 2946 // case <NumSection> - 1: 2947 // <SectionStmt[<NumSection> - 1]>; 2948 // break; 2949 // } 2950 // .omp.sections.exit: 2951 llvm::BasicBlock *ExitBB = CGF.createBasicBlock(".omp.sections.exit"); 2952 llvm::SwitchInst *SwitchStmt = 2953 CGF.Builder.CreateSwitch(CGF.EmitLoadOfScalar(IV, S.getBeginLoc()), 2954 ExitBB, CS == nullptr ? 1 : CS->size()); 2955 if (CS) { 2956 unsigned CaseNumber = 0; 2957 for (const Stmt *SubStmt : CS->children()) { 2958 auto CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2959 CGF.EmitBlock(CaseBB); 2960 SwitchStmt->addCase(CGF.Builder.getInt32(CaseNumber), CaseBB); 2961 CGF.EmitStmt(SubStmt); 2962 CGF.EmitBranch(ExitBB); 2963 ++CaseNumber; 2964 } 2965 } else { 2966 llvm::BasicBlock *CaseBB = CGF.createBasicBlock(".omp.sections.case"); 2967 CGF.EmitBlock(CaseBB); 2968 SwitchStmt->addCase(CGF.Builder.getInt32(0), CaseBB); 2969 CGF.EmitStmt(CapturedStmt); 2970 CGF.EmitBranch(ExitBB); 2971 } 2972 CGF.EmitBlock(ExitBB, /*IsFinished=*/true); 2973 }; 2974 2975 CodeGenFunction::OMPPrivateScope LoopScope(CGF); 2976 if (CGF.EmitOMPFirstprivateClause(S, LoopScope)) { 2977 // Emit implicit barrier to synchronize threads and avoid data races on 2978 // initialization of firstprivate variables and post-update of lastprivate 2979 // variables. 2980 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 2981 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 2982 /*ForceSimpleCall=*/true); 2983 } 2984 CGF.EmitOMPPrivateClause(S, LoopScope); 2985 CGOpenMPRuntime::LastprivateConditionalRAII LPCRegion(CGF, S, IV); 2986 HasLastprivates = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 2987 CGF.EmitOMPReductionClauseInit(S, LoopScope); 2988 (void)LoopScope.Privatize(); 2989 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 2990 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 2991 2992 // Emit static non-chunked loop. 2993 OpenMPScheduleTy ScheduleKind; 2994 ScheduleKind.Schedule = OMPC_SCHEDULE_static; 2995 CGOpenMPRuntime::StaticRTInput StaticInit( 2996 /*IVSize=*/32, /*IVSigned=*/true, /*Ordered=*/false, IL.getAddress(CGF), 2997 LB.getAddress(CGF), UB.getAddress(CGF), ST.getAddress(CGF)); 2998 CGF.CGM.getOpenMPRuntime().emitForStaticInit( 2999 CGF, S.getBeginLoc(), S.getDirectiveKind(), ScheduleKind, StaticInit); 3000 // UB = min(UB, GlobalUB); 3001 llvm::Value *UBVal = CGF.EmitLoadOfScalar(UB, S.getBeginLoc()); 3002 llvm::Value *MinUBGlobalUB = CGF.Builder.CreateSelect( 3003 CGF.Builder.CreateICmpSLT(UBVal, GlobalUBVal), UBVal, GlobalUBVal); 3004 CGF.EmitStoreOfScalar(MinUBGlobalUB, UB); 3005 // IV = LB; 3006 CGF.EmitStoreOfScalar(CGF.EmitLoadOfScalar(LB, S.getBeginLoc()), IV); 3007 // while (idx <= UB) { BODY; ++idx; } 3008 CGF.EmitOMPInnerLoop(S, /*RequiresCleanup=*/false, Cond, &Inc, BodyGen, 3009 [](CodeGenFunction &) {}); 3010 // Tell the runtime we are done. 3011 auto &&CodeGen = [&S](CodeGenFunction &CGF) { 3012 CGF.CGM.getOpenMPRuntime().emitForStaticFinish(CGF, S.getEndLoc(), 3013 S.getDirectiveKind()); 3014 }; 3015 CGF.OMPCancelStack.emitExit(CGF, S.getDirectiveKind(), CodeGen); 3016 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3017 // Emit post-update of the reduction variables if IsLastIter != 0. 3018 emitPostUpdateForReductionClause(CGF, S, [IL, &S](CodeGenFunction &CGF) { 3019 return CGF.Builder.CreateIsNotNull( 3020 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 3021 }); 3022 3023 // Emit final copy of the lastprivate variables if IsLastIter != 0. 3024 if (HasLastprivates) 3025 CGF.EmitOMPLastprivateClauseFinal( 3026 S, /*NoFinals=*/false, 3027 CGF.Builder.CreateIsNotNull( 3028 CGF.EmitLoadOfScalar(IL, S.getBeginLoc()))); 3029 }; 3030 3031 bool HasCancel = false; 3032 if (auto *OSD = dyn_cast<OMPSectionsDirective>(&S)) 3033 HasCancel = OSD->hasCancel(); 3034 else if (auto *OPSD = dyn_cast<OMPParallelSectionsDirective>(&S)) 3035 HasCancel = OPSD->hasCancel(); 3036 OMPCancelStackRAII CancelRegion(*this, S.getDirectiveKind(), HasCancel); 3037 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_sections, CodeGen, 3038 HasCancel); 3039 // Emit barrier for lastprivates only if 'sections' directive has 'nowait' 3040 // clause. Otherwise the barrier will be generated by the codegen for the 3041 // directive. 3042 if (HasLastprivates && S.getSingleClause<OMPNowaitClause>()) { 3043 // Emit implicit barrier to synchronize threads and avoid data races on 3044 // initialization of firstprivate variables. 3045 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3046 OMPD_unknown); 3047 } 3048 } 3049 3050 void CodeGenFunction::EmitOMPSectionsDirective(const OMPSectionsDirective &S) { 3051 { 3052 auto LPCRegion = 3053 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3054 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3055 EmitSections(S); 3056 } 3057 // Emit an implicit barrier at the end. 3058 if (!S.getSingleClause<OMPNowaitClause>()) { 3059 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), 3060 OMPD_sections); 3061 } 3062 // Check for outer lastprivate conditional update. 3063 checkForLastprivateConditionalUpdate(*this, S); 3064 } 3065 3066 void CodeGenFunction::EmitOMPSectionDirective(const OMPSectionDirective &S) { 3067 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 3068 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3069 }; 3070 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3071 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_section, CodeGen, 3072 S.hasCancel()); 3073 } 3074 3075 void CodeGenFunction::EmitOMPSingleDirective(const OMPSingleDirective &S) { 3076 llvm::SmallVector<const Expr *, 8> CopyprivateVars; 3077 llvm::SmallVector<const Expr *, 8> DestExprs; 3078 llvm::SmallVector<const Expr *, 8> SrcExprs; 3079 llvm::SmallVector<const Expr *, 8> AssignmentOps; 3080 // Check if there are any 'copyprivate' clauses associated with this 3081 // 'single' construct. 3082 // Build a list of copyprivate variables along with helper expressions 3083 // (<source>, <destination>, <destination>=<source> expressions) 3084 for (const auto *C : S.getClausesOfKind<OMPCopyprivateClause>()) { 3085 CopyprivateVars.append(C->varlists().begin(), C->varlists().end()); 3086 DestExprs.append(C->destination_exprs().begin(), 3087 C->destination_exprs().end()); 3088 SrcExprs.append(C->source_exprs().begin(), C->source_exprs().end()); 3089 AssignmentOps.append(C->assignment_ops().begin(), 3090 C->assignment_ops().end()); 3091 } 3092 // Emit code for 'single' region along with 'copyprivate' clauses 3093 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3094 Action.Enter(CGF); 3095 OMPPrivateScope SingleScope(CGF); 3096 (void)CGF.EmitOMPFirstprivateClause(S, SingleScope); 3097 CGF.EmitOMPPrivateClause(S, SingleScope); 3098 (void)SingleScope.Privatize(); 3099 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3100 }; 3101 { 3102 auto LPCRegion = 3103 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3104 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3105 CGM.getOpenMPRuntime().emitSingleRegion(*this, CodeGen, S.getBeginLoc(), 3106 CopyprivateVars, DestExprs, 3107 SrcExprs, AssignmentOps); 3108 } 3109 // Emit an implicit barrier at the end (to avoid data race on firstprivate 3110 // init or if no 'nowait' clause was specified and no 'copyprivate' clause). 3111 if (!S.getSingleClause<OMPNowaitClause>() && CopyprivateVars.empty()) { 3112 CGM.getOpenMPRuntime().emitBarrierCall( 3113 *this, S.getBeginLoc(), 3114 S.getSingleClause<OMPNowaitClause>() ? OMPD_unknown : OMPD_single); 3115 } 3116 // Check for outer lastprivate conditional update. 3117 checkForLastprivateConditionalUpdate(*this, S); 3118 } 3119 3120 static void emitMaster(CodeGenFunction &CGF, const OMPExecutableDirective &S) { 3121 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3122 Action.Enter(CGF); 3123 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3124 }; 3125 CGF.CGM.getOpenMPRuntime().emitMasterRegion(CGF, CodeGen, S.getBeginLoc()); 3126 } 3127 3128 void CodeGenFunction::EmitOMPMasterDirective(const OMPMasterDirective &S) { 3129 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 3130 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3131 3132 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 3133 const Stmt *MasterRegionBodyStmt = CS->getCapturedStmt(); 3134 3135 auto FiniCB = [this](InsertPointTy IP) { 3136 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3137 }; 3138 3139 auto BodyGenCB = [MasterRegionBodyStmt, this](InsertPointTy AllocaIP, 3140 InsertPointTy CodeGenIP, 3141 llvm::BasicBlock &FiniBB) { 3142 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3143 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, MasterRegionBodyStmt, 3144 CodeGenIP, FiniBB); 3145 }; 3146 3147 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 3148 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 3149 Builder.restoreIP(OMPBuilder->CreateMaster(Builder, BodyGenCB, FiniCB)); 3150 3151 return; 3152 } 3153 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3154 emitMaster(*this, S); 3155 } 3156 3157 void CodeGenFunction::EmitOMPCriticalDirective(const OMPCriticalDirective &S) { 3158 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 3159 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 3160 3161 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 3162 const Stmt *CriticalRegionBodyStmt = CS->getCapturedStmt(); 3163 const Expr *Hint = nullptr; 3164 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 3165 Hint = HintClause->getHint(); 3166 3167 // TODO: This is slightly different from what's currently being done in 3168 // clang. Fix the Int32Ty to IntPtrTy (pointer width size) when everything 3169 // about typing is final. 3170 llvm::Value *HintInst = nullptr; 3171 if (Hint) 3172 HintInst = 3173 Builder.CreateIntCast(EmitScalarExpr(Hint), CGM.Int32Ty, false); 3174 3175 auto FiniCB = [this](InsertPointTy IP) { 3176 OMPBuilderCBHelpers::FinalizeOMPRegion(*this, IP); 3177 }; 3178 3179 auto BodyGenCB = [CriticalRegionBodyStmt, this](InsertPointTy AllocaIP, 3180 InsertPointTy CodeGenIP, 3181 llvm::BasicBlock &FiniBB) { 3182 OMPBuilderCBHelpers::InlinedRegionBodyRAII IRB(*this, AllocaIP, FiniBB); 3183 OMPBuilderCBHelpers::EmitOMPRegionBody(*this, CriticalRegionBodyStmt, 3184 CodeGenIP, FiniBB); 3185 }; 3186 3187 CGCapturedStmtInfo CGSI(*CS, CR_OpenMP); 3188 CodeGenFunction::CGCapturedStmtRAII CapInfoRAII(*this, &CGSI); 3189 Builder.restoreIP(OMPBuilder->CreateCritical( 3190 Builder, BodyGenCB, FiniCB, S.getDirectiveName().getAsString(), 3191 HintInst)); 3192 3193 return; 3194 } 3195 3196 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3197 Action.Enter(CGF); 3198 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3199 }; 3200 const Expr *Hint = nullptr; 3201 if (const auto *HintClause = S.getSingleClause<OMPHintClause>()) 3202 Hint = HintClause->getHint(); 3203 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3204 CGM.getOpenMPRuntime().emitCriticalRegion(*this, 3205 S.getDirectiveName().getAsString(), 3206 CodeGen, S.getBeginLoc(), Hint); 3207 } 3208 3209 void CodeGenFunction::EmitOMPParallelForDirective( 3210 const OMPParallelForDirective &S) { 3211 // Emit directive as a combined directive that consists of two implicit 3212 // directives: 'parallel' with 'for' directive. 3213 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3214 Action.Enter(CGF); 3215 OMPCancelStackRAII CancelRegion(CGF, OMPD_parallel_for, S.hasCancel()); 3216 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 3217 emitDispatchForLoopBounds); 3218 }; 3219 { 3220 auto LPCRegion = 3221 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3222 emitCommonOMPParallelDirective(*this, S, OMPD_for, CodeGen, 3223 emitEmptyBoundParameters); 3224 } 3225 // Check for outer lastprivate conditional update. 3226 checkForLastprivateConditionalUpdate(*this, S); 3227 } 3228 3229 void CodeGenFunction::EmitOMPParallelForSimdDirective( 3230 const OMPParallelForSimdDirective &S) { 3231 // Emit directive as a combined directive that consists of two implicit 3232 // directives: 'parallel' with 'for' directive. 3233 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3234 Action.Enter(CGF); 3235 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 3236 emitDispatchForLoopBounds); 3237 }; 3238 { 3239 auto LPCRegion = 3240 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3241 emitCommonOMPParallelDirective(*this, S, OMPD_simd, CodeGen, 3242 emitEmptyBoundParameters); 3243 } 3244 // Check for outer lastprivate conditional update. 3245 checkForLastprivateConditionalUpdate(*this, S); 3246 } 3247 3248 void CodeGenFunction::EmitOMPParallelMasterDirective( 3249 const OMPParallelMasterDirective &S) { 3250 // Emit directive as a combined directive that consists of two implicit 3251 // directives: 'parallel' with 'master' directive. 3252 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3253 Action.Enter(CGF); 3254 OMPPrivateScope PrivateScope(CGF); 3255 bool Copyins = CGF.EmitOMPCopyinClause(S); 3256 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 3257 if (Copyins) { 3258 // Emit implicit barrier to synchronize threads and avoid data races on 3259 // propagation master's thread values of threadprivate variables to local 3260 // instances of that variables of all other implicit threads. 3261 CGF.CGM.getOpenMPRuntime().emitBarrierCall( 3262 CGF, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3263 /*ForceSimpleCall=*/true); 3264 } 3265 CGF.EmitOMPPrivateClause(S, PrivateScope); 3266 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 3267 (void)PrivateScope.Privatize(); 3268 emitMaster(CGF, S); 3269 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 3270 }; 3271 { 3272 auto LPCRegion = 3273 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3274 emitCommonOMPParallelDirective(*this, S, OMPD_master, CodeGen, 3275 emitEmptyBoundParameters); 3276 emitPostUpdateForReductionClause(*this, S, 3277 [](CodeGenFunction &) { return nullptr; }); 3278 } 3279 // Check for outer lastprivate conditional update. 3280 checkForLastprivateConditionalUpdate(*this, S); 3281 } 3282 3283 void CodeGenFunction::EmitOMPParallelSectionsDirective( 3284 const OMPParallelSectionsDirective &S) { 3285 // Emit directive as a combined directive that consists of two implicit 3286 // directives: 'parallel' with 'sections' directive. 3287 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3288 Action.Enter(CGF); 3289 CGF.EmitSections(S); 3290 }; 3291 { 3292 auto LPCRegion = 3293 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3294 emitCommonOMPParallelDirective(*this, S, OMPD_sections, CodeGen, 3295 emitEmptyBoundParameters); 3296 } 3297 // Check for outer lastprivate conditional update. 3298 checkForLastprivateConditionalUpdate(*this, S); 3299 } 3300 3301 void CodeGenFunction::EmitOMPTaskBasedDirective( 3302 const OMPExecutableDirective &S, const OpenMPDirectiveKind CapturedRegion, 3303 const RegionCodeGenTy &BodyGen, const TaskGenTy &TaskGen, 3304 OMPTaskDataTy &Data) { 3305 // Emit outlined function for task construct. 3306 const CapturedStmt *CS = S.getCapturedStmt(CapturedRegion); 3307 auto I = CS->getCapturedDecl()->param_begin(); 3308 auto PartId = std::next(I); 3309 auto TaskT = std::next(I, 4); 3310 // Check if the task is final 3311 if (const auto *Clause = S.getSingleClause<OMPFinalClause>()) { 3312 // If the condition constant folds and can be elided, try to avoid emitting 3313 // the condition and the dead arm of the if/else. 3314 const Expr *Cond = Clause->getCondition(); 3315 bool CondConstant; 3316 if (ConstantFoldsToSimpleInteger(Cond, CondConstant)) 3317 Data.Final.setInt(CondConstant); 3318 else 3319 Data.Final.setPointer(EvaluateExprAsBool(Cond)); 3320 } else { 3321 // By default the task is not final. 3322 Data.Final.setInt(/*IntVal=*/false); 3323 } 3324 // Check if the task has 'priority' clause. 3325 if (const auto *Clause = S.getSingleClause<OMPPriorityClause>()) { 3326 const Expr *Prio = Clause->getPriority(); 3327 Data.Priority.setInt(/*IntVal=*/true); 3328 Data.Priority.setPointer(EmitScalarConversion( 3329 EmitScalarExpr(Prio), Prio->getType(), 3330 getContext().getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1), 3331 Prio->getExprLoc())); 3332 } 3333 // The first function argument for tasks is a thread id, the second one is a 3334 // part id (0 for tied tasks, >=0 for untied task). 3335 llvm::DenseSet<const VarDecl *> EmittedAsPrivate; 3336 // Get list of private variables. 3337 for (const auto *C : S.getClausesOfKind<OMPPrivateClause>()) { 3338 auto IRef = C->varlist_begin(); 3339 for (const Expr *IInit : C->private_copies()) { 3340 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3341 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3342 Data.PrivateVars.push_back(*IRef); 3343 Data.PrivateCopies.push_back(IInit); 3344 } 3345 ++IRef; 3346 } 3347 } 3348 EmittedAsPrivate.clear(); 3349 // Get list of firstprivate variables. 3350 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 3351 auto IRef = C->varlist_begin(); 3352 auto IElemInitRef = C->inits().begin(); 3353 for (const Expr *IInit : C->private_copies()) { 3354 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3355 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3356 Data.FirstprivateVars.push_back(*IRef); 3357 Data.FirstprivateCopies.push_back(IInit); 3358 Data.FirstprivateInits.push_back(*IElemInitRef); 3359 } 3360 ++IRef; 3361 ++IElemInitRef; 3362 } 3363 } 3364 // Get list of lastprivate variables (for taskloops). 3365 llvm::DenseMap<const VarDecl *, const DeclRefExpr *> LastprivateDstsOrigs; 3366 for (const auto *C : S.getClausesOfKind<OMPLastprivateClause>()) { 3367 auto IRef = C->varlist_begin(); 3368 auto ID = C->destination_exprs().begin(); 3369 for (const Expr *IInit : C->private_copies()) { 3370 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*IRef)->getDecl()); 3371 if (EmittedAsPrivate.insert(OrigVD->getCanonicalDecl()).second) { 3372 Data.LastprivateVars.push_back(*IRef); 3373 Data.LastprivateCopies.push_back(IInit); 3374 } 3375 LastprivateDstsOrigs.insert( 3376 {cast<VarDecl>(cast<DeclRefExpr>(*ID)->getDecl()), 3377 cast<DeclRefExpr>(*IRef)}); 3378 ++IRef; 3379 ++ID; 3380 } 3381 } 3382 SmallVector<const Expr *, 4> LHSs; 3383 SmallVector<const Expr *, 4> RHSs; 3384 for (const auto *C : S.getClausesOfKind<OMPReductionClause>()) { 3385 auto IPriv = C->privates().begin(); 3386 auto IRed = C->reduction_ops().begin(); 3387 auto ILHS = C->lhs_exprs().begin(); 3388 auto IRHS = C->rhs_exprs().begin(); 3389 for (const Expr *Ref : C->varlists()) { 3390 Data.ReductionVars.emplace_back(Ref); 3391 Data.ReductionCopies.emplace_back(*IPriv); 3392 Data.ReductionOps.emplace_back(*IRed); 3393 LHSs.emplace_back(*ILHS); 3394 RHSs.emplace_back(*IRHS); 3395 std::advance(IPriv, 1); 3396 std::advance(IRed, 1); 3397 std::advance(ILHS, 1); 3398 std::advance(IRHS, 1); 3399 } 3400 } 3401 Data.Reductions = CGM.getOpenMPRuntime().emitTaskReductionInit( 3402 *this, S.getBeginLoc(), LHSs, RHSs, Data); 3403 // Build list of dependences. 3404 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 3405 OMPTaskDataTy::DependData &DD = 3406 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 3407 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 3408 } 3409 auto &&CodeGen = [&Data, &S, CS, &BodyGen, &LastprivateDstsOrigs, 3410 CapturedRegion](CodeGenFunction &CGF, 3411 PrePostActionTy &Action) { 3412 // Set proper addresses for generated private copies. 3413 OMPPrivateScope Scope(CGF); 3414 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> FirstprivatePtrs; 3415 if (!Data.PrivateVars.empty() || !Data.FirstprivateVars.empty() || 3416 !Data.LastprivateVars.empty()) { 3417 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 3418 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 3419 enum { PrivatesParam = 2, CopyFnParam = 3 }; 3420 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 3421 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 3422 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 3423 CS->getCapturedDecl()->getParam(PrivatesParam))); 3424 // Map privates. 3425 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 3426 llvm::SmallVector<llvm::Value *, 16> CallArgs; 3427 CallArgs.push_back(PrivatesPtr); 3428 for (const Expr *E : Data.PrivateVars) { 3429 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3430 Address PrivatePtr = CGF.CreateMemTemp( 3431 CGF.getContext().getPointerType(E->getType()), ".priv.ptr.addr"); 3432 PrivatePtrs.emplace_back(VD, PrivatePtr); 3433 CallArgs.push_back(PrivatePtr.getPointer()); 3434 } 3435 for (const Expr *E : Data.FirstprivateVars) { 3436 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3437 Address PrivatePtr = 3438 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3439 ".firstpriv.ptr.addr"); 3440 PrivatePtrs.emplace_back(VD, PrivatePtr); 3441 FirstprivatePtrs.emplace_back(VD, PrivatePtr); 3442 CallArgs.push_back(PrivatePtr.getPointer()); 3443 } 3444 for (const Expr *E : Data.LastprivateVars) { 3445 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3446 Address PrivatePtr = 3447 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3448 ".lastpriv.ptr.addr"); 3449 PrivatePtrs.emplace_back(VD, PrivatePtr); 3450 CallArgs.push_back(PrivatePtr.getPointer()); 3451 } 3452 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 3453 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 3454 for (const auto &Pair : LastprivateDstsOrigs) { 3455 const auto *OrigVD = cast<VarDecl>(Pair.second->getDecl()); 3456 DeclRefExpr DRE(CGF.getContext(), const_cast<VarDecl *>(OrigVD), 3457 /*RefersToEnclosingVariableOrCapture=*/ 3458 CGF.CapturedStmtInfo->lookup(OrigVD) != nullptr, 3459 Pair.second->getType(), VK_LValue, 3460 Pair.second->getExprLoc()); 3461 Scope.addPrivate(Pair.first, [&CGF, &DRE]() { 3462 return CGF.EmitLValue(&DRE).getAddress(CGF); 3463 }); 3464 } 3465 for (const auto &Pair : PrivatePtrs) { 3466 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 3467 CGF.getContext().getDeclAlign(Pair.first)); 3468 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 3469 } 3470 } 3471 if (Data.Reductions) { 3472 OMPPrivateScope FirstprivateScope(CGF); 3473 for (const auto &Pair : FirstprivatePtrs) { 3474 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 3475 CGF.getContext().getDeclAlign(Pair.first)); 3476 FirstprivateScope.addPrivate(Pair.first, 3477 [Replacement]() { return Replacement; }); 3478 } 3479 (void)FirstprivateScope.Privatize(); 3480 OMPLexicalScope LexScope(CGF, S, CapturedRegion); 3481 ReductionCodeGen RedCG(Data.ReductionVars, Data.ReductionCopies, 3482 Data.ReductionOps); 3483 llvm::Value *ReductionsPtr = CGF.Builder.CreateLoad( 3484 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(9))); 3485 for (unsigned Cnt = 0, E = Data.ReductionVars.size(); Cnt < E; ++Cnt) { 3486 RedCG.emitSharedLValue(CGF, Cnt); 3487 RedCG.emitAggregateType(CGF, Cnt); 3488 // FIXME: This must removed once the runtime library is fixed. 3489 // Emit required threadprivate variables for 3490 // initializer/combiner/finalizer. 3491 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 3492 RedCG, Cnt); 3493 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 3494 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 3495 Replacement = 3496 Address(CGF.EmitScalarConversion( 3497 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 3498 CGF.getContext().getPointerType( 3499 Data.ReductionCopies[Cnt]->getType()), 3500 Data.ReductionCopies[Cnt]->getExprLoc()), 3501 Replacement.getAlignment()); 3502 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 3503 Scope.addPrivate(RedCG.getBaseDecl(Cnt), 3504 [Replacement]() { return Replacement; }); 3505 } 3506 } 3507 // Privatize all private variables except for in_reduction items. 3508 (void)Scope.Privatize(); 3509 SmallVector<const Expr *, 4> InRedVars; 3510 SmallVector<const Expr *, 4> InRedPrivs; 3511 SmallVector<const Expr *, 4> InRedOps; 3512 SmallVector<const Expr *, 4> TaskgroupDescriptors; 3513 for (const auto *C : S.getClausesOfKind<OMPInReductionClause>()) { 3514 auto IPriv = C->privates().begin(); 3515 auto IRed = C->reduction_ops().begin(); 3516 auto ITD = C->taskgroup_descriptors().begin(); 3517 for (const Expr *Ref : C->varlists()) { 3518 InRedVars.emplace_back(Ref); 3519 InRedPrivs.emplace_back(*IPriv); 3520 InRedOps.emplace_back(*IRed); 3521 TaskgroupDescriptors.emplace_back(*ITD); 3522 std::advance(IPriv, 1); 3523 std::advance(IRed, 1); 3524 std::advance(ITD, 1); 3525 } 3526 } 3527 // Privatize in_reduction items here, because taskgroup descriptors must be 3528 // privatized earlier. 3529 OMPPrivateScope InRedScope(CGF); 3530 if (!InRedVars.empty()) { 3531 ReductionCodeGen RedCG(InRedVars, InRedPrivs, InRedOps); 3532 for (unsigned Cnt = 0, E = InRedVars.size(); Cnt < E; ++Cnt) { 3533 RedCG.emitSharedLValue(CGF, Cnt); 3534 RedCG.emitAggregateType(CGF, Cnt); 3535 // The taskgroup descriptor variable is always implicit firstprivate and 3536 // privatized already during processing of the firstprivates. 3537 // FIXME: This must removed once the runtime library is fixed. 3538 // Emit required threadprivate variables for 3539 // initializer/combiner/finalizer. 3540 CGF.CGM.getOpenMPRuntime().emitTaskReductionFixups(CGF, S.getBeginLoc(), 3541 RedCG, Cnt); 3542 llvm::Value *ReductionsPtr; 3543 if (const Expr *TRExpr = TaskgroupDescriptors[Cnt]) { 3544 ReductionsPtr = CGF.EmitLoadOfScalar(CGF.EmitLValue(TRExpr), 3545 TRExpr->getExprLoc()); 3546 } else { 3547 ReductionsPtr = llvm::ConstantPointerNull::get(CGF.VoidPtrTy); 3548 } 3549 Address Replacement = CGF.CGM.getOpenMPRuntime().getTaskReductionItem( 3550 CGF, S.getBeginLoc(), ReductionsPtr, RedCG.getSharedLValue(Cnt)); 3551 Replacement = Address( 3552 CGF.EmitScalarConversion( 3553 Replacement.getPointer(), CGF.getContext().VoidPtrTy, 3554 CGF.getContext().getPointerType(InRedPrivs[Cnt]->getType()), 3555 InRedPrivs[Cnt]->getExprLoc()), 3556 Replacement.getAlignment()); 3557 Replacement = RedCG.adjustPrivateAddress(CGF, Cnt, Replacement); 3558 InRedScope.addPrivate(RedCG.getBaseDecl(Cnt), 3559 [Replacement]() { return Replacement; }); 3560 } 3561 } 3562 (void)InRedScope.Privatize(); 3563 3564 Action.Enter(CGF); 3565 BodyGen(CGF); 3566 }; 3567 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 3568 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, Data.Tied, 3569 Data.NumberOfParts); 3570 OMPLexicalScope Scope(*this, S, llvm::None, 3571 !isOpenMPParallelDirective(S.getDirectiveKind()) && 3572 !isOpenMPSimdDirective(S.getDirectiveKind())); 3573 TaskGen(*this, OutlinedFn, Data); 3574 } 3575 3576 static ImplicitParamDecl * 3577 createImplicitFirstprivateForType(ASTContext &C, OMPTaskDataTy &Data, 3578 QualType Ty, CapturedDecl *CD, 3579 SourceLocation Loc) { 3580 auto *OrigVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 3581 ImplicitParamDecl::Other); 3582 auto *OrigRef = DeclRefExpr::Create( 3583 C, NestedNameSpecifierLoc(), SourceLocation(), OrigVD, 3584 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 3585 auto *PrivateVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, Ty, 3586 ImplicitParamDecl::Other); 3587 auto *PrivateRef = DeclRefExpr::Create( 3588 C, NestedNameSpecifierLoc(), SourceLocation(), PrivateVD, 3589 /*RefersToEnclosingVariableOrCapture=*/false, Loc, Ty, VK_LValue); 3590 QualType ElemType = C.getBaseElementType(Ty); 3591 auto *InitVD = ImplicitParamDecl::Create(C, CD, Loc, /*Id=*/nullptr, ElemType, 3592 ImplicitParamDecl::Other); 3593 auto *InitRef = DeclRefExpr::Create( 3594 C, NestedNameSpecifierLoc(), SourceLocation(), InitVD, 3595 /*RefersToEnclosingVariableOrCapture=*/false, Loc, ElemType, VK_LValue); 3596 PrivateVD->setInitStyle(VarDecl::CInit); 3597 PrivateVD->setInit(ImplicitCastExpr::Create(C, ElemType, CK_LValueToRValue, 3598 InitRef, /*BasePath=*/nullptr, 3599 VK_RValue)); 3600 Data.FirstprivateVars.emplace_back(OrigRef); 3601 Data.FirstprivateCopies.emplace_back(PrivateRef); 3602 Data.FirstprivateInits.emplace_back(InitRef); 3603 return OrigVD; 3604 } 3605 3606 void CodeGenFunction::EmitOMPTargetTaskBasedDirective( 3607 const OMPExecutableDirective &S, const RegionCodeGenTy &BodyGen, 3608 OMPTargetDataInfo &InputInfo) { 3609 // Emit outlined function for task construct. 3610 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 3611 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 3612 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 3613 auto I = CS->getCapturedDecl()->param_begin(); 3614 auto PartId = std::next(I); 3615 auto TaskT = std::next(I, 4); 3616 OMPTaskDataTy Data; 3617 // The task is not final. 3618 Data.Final.setInt(/*IntVal=*/false); 3619 // Get list of firstprivate variables. 3620 for (const auto *C : S.getClausesOfKind<OMPFirstprivateClause>()) { 3621 auto IRef = C->varlist_begin(); 3622 auto IElemInitRef = C->inits().begin(); 3623 for (auto *IInit : C->private_copies()) { 3624 Data.FirstprivateVars.push_back(*IRef); 3625 Data.FirstprivateCopies.push_back(IInit); 3626 Data.FirstprivateInits.push_back(*IElemInitRef); 3627 ++IRef; 3628 ++IElemInitRef; 3629 } 3630 } 3631 OMPPrivateScope TargetScope(*this); 3632 VarDecl *BPVD = nullptr; 3633 VarDecl *PVD = nullptr; 3634 VarDecl *SVD = nullptr; 3635 if (InputInfo.NumberOfTargetItems > 0) { 3636 auto *CD = CapturedDecl::Create( 3637 getContext(), getContext().getTranslationUnitDecl(), /*NumParams=*/0); 3638 llvm::APInt ArrSize(/*numBits=*/32, InputInfo.NumberOfTargetItems); 3639 QualType BaseAndPointersType = getContext().getConstantArrayType( 3640 getContext().VoidPtrTy, ArrSize, nullptr, ArrayType::Normal, 3641 /*IndexTypeQuals=*/0); 3642 BPVD = createImplicitFirstprivateForType( 3643 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc()); 3644 PVD = createImplicitFirstprivateForType( 3645 getContext(), Data, BaseAndPointersType, CD, S.getBeginLoc()); 3646 QualType SizesType = getContext().getConstantArrayType( 3647 getContext().getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1), 3648 ArrSize, nullptr, ArrayType::Normal, 3649 /*IndexTypeQuals=*/0); 3650 SVD = createImplicitFirstprivateForType(getContext(), Data, SizesType, CD, 3651 S.getBeginLoc()); 3652 TargetScope.addPrivate( 3653 BPVD, [&InputInfo]() { return InputInfo.BasePointersArray; }); 3654 TargetScope.addPrivate(PVD, 3655 [&InputInfo]() { return InputInfo.PointersArray; }); 3656 TargetScope.addPrivate(SVD, 3657 [&InputInfo]() { return InputInfo.SizesArray; }); 3658 } 3659 (void)TargetScope.Privatize(); 3660 // Build list of dependences. 3661 for (const auto *C : S.getClausesOfKind<OMPDependClause>()) { 3662 OMPTaskDataTy::DependData &DD = 3663 Data.Dependences.emplace_back(C->getDependencyKind(), C->getModifier()); 3664 DD.DepExprs.append(C->varlist_begin(), C->varlist_end()); 3665 } 3666 auto &&CodeGen = [&Data, &S, CS, &BodyGen, BPVD, PVD, SVD, 3667 &InputInfo](CodeGenFunction &CGF, PrePostActionTy &Action) { 3668 // Set proper addresses for generated private copies. 3669 OMPPrivateScope Scope(CGF); 3670 if (!Data.FirstprivateVars.empty()) { 3671 llvm::FunctionType *CopyFnTy = llvm::FunctionType::get( 3672 CGF.Builder.getVoidTy(), {CGF.Builder.getInt8PtrTy()}, true); 3673 enum { PrivatesParam = 2, CopyFnParam = 3 }; 3674 llvm::Value *CopyFn = CGF.Builder.CreateLoad( 3675 CGF.GetAddrOfLocalVar(CS->getCapturedDecl()->getParam(CopyFnParam))); 3676 llvm::Value *PrivatesPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar( 3677 CS->getCapturedDecl()->getParam(PrivatesParam))); 3678 // Map privates. 3679 llvm::SmallVector<std::pair<const VarDecl *, Address>, 16> PrivatePtrs; 3680 llvm::SmallVector<llvm::Value *, 16> CallArgs; 3681 CallArgs.push_back(PrivatesPtr); 3682 for (const Expr *E : Data.FirstprivateVars) { 3683 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3684 Address PrivatePtr = 3685 CGF.CreateMemTemp(CGF.getContext().getPointerType(E->getType()), 3686 ".firstpriv.ptr.addr"); 3687 PrivatePtrs.emplace_back(VD, PrivatePtr); 3688 CallArgs.push_back(PrivatePtr.getPointer()); 3689 } 3690 CGF.CGM.getOpenMPRuntime().emitOutlinedFunctionCall( 3691 CGF, S.getBeginLoc(), {CopyFnTy, CopyFn}, CallArgs); 3692 for (const auto &Pair : PrivatePtrs) { 3693 Address Replacement(CGF.Builder.CreateLoad(Pair.second), 3694 CGF.getContext().getDeclAlign(Pair.first)); 3695 Scope.addPrivate(Pair.first, [Replacement]() { return Replacement; }); 3696 } 3697 } 3698 // Privatize all private variables except for in_reduction items. 3699 (void)Scope.Privatize(); 3700 if (InputInfo.NumberOfTargetItems > 0) { 3701 InputInfo.BasePointersArray = CGF.Builder.CreateConstArrayGEP( 3702 CGF.GetAddrOfLocalVar(BPVD), /*Index=*/0); 3703 InputInfo.PointersArray = CGF.Builder.CreateConstArrayGEP( 3704 CGF.GetAddrOfLocalVar(PVD), /*Index=*/0); 3705 InputInfo.SizesArray = CGF.Builder.CreateConstArrayGEP( 3706 CGF.GetAddrOfLocalVar(SVD), /*Index=*/0); 3707 } 3708 3709 Action.Enter(CGF); 3710 OMPLexicalScope LexScope(CGF, S, OMPD_task, /*EmitPreInitStmt=*/false); 3711 BodyGen(CGF); 3712 }; 3713 llvm::Function *OutlinedFn = CGM.getOpenMPRuntime().emitTaskOutlinedFunction( 3714 S, *I, *PartId, *TaskT, S.getDirectiveKind(), CodeGen, /*Tied=*/true, 3715 Data.NumberOfParts); 3716 llvm::APInt TrueOrFalse(32, S.hasClausesOfKind<OMPNowaitClause>() ? 1 : 0); 3717 IntegerLiteral IfCond(getContext(), TrueOrFalse, 3718 getContext().getIntTypeForBitwidth(32, /*Signed=*/0), 3719 SourceLocation()); 3720 3721 CGM.getOpenMPRuntime().emitTaskCall(*this, S.getBeginLoc(), S, OutlinedFn, 3722 SharedsTy, CapturedStruct, &IfCond, Data); 3723 } 3724 3725 void CodeGenFunction::EmitOMPTaskDirective(const OMPTaskDirective &S) { 3726 // Emit outlined function for task construct. 3727 const CapturedStmt *CS = S.getCapturedStmt(OMPD_task); 3728 Address CapturedStruct = GenerateCapturedStmtArgument(*CS); 3729 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 3730 const Expr *IfCond = nullptr; 3731 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 3732 if (C->getNameModifier() == OMPD_unknown || 3733 C->getNameModifier() == OMPD_task) { 3734 IfCond = C->getCondition(); 3735 break; 3736 } 3737 } 3738 3739 OMPTaskDataTy Data; 3740 // Check if we should emit tied or untied task. 3741 Data.Tied = !S.getSingleClause<OMPUntiedClause>(); 3742 auto &&BodyGen = [CS](CodeGenFunction &CGF, PrePostActionTy &) { 3743 CGF.EmitStmt(CS->getCapturedStmt()); 3744 }; 3745 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 3746 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 3747 const OMPTaskDataTy &Data) { 3748 CGF.CGM.getOpenMPRuntime().emitTaskCall(CGF, S.getBeginLoc(), S, OutlinedFn, 3749 SharedsTy, CapturedStruct, IfCond, 3750 Data); 3751 }; 3752 auto LPCRegion = 3753 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 3754 EmitOMPTaskBasedDirective(S, OMPD_task, BodyGen, TaskGen, Data); 3755 } 3756 3757 void CodeGenFunction::EmitOMPTaskyieldDirective( 3758 const OMPTaskyieldDirective &S) { 3759 CGM.getOpenMPRuntime().emitTaskyieldCall(*this, S.getBeginLoc()); 3760 } 3761 3762 void CodeGenFunction::EmitOMPBarrierDirective(const OMPBarrierDirective &S) { 3763 CGM.getOpenMPRuntime().emitBarrierCall(*this, S.getBeginLoc(), OMPD_barrier); 3764 } 3765 3766 void CodeGenFunction::EmitOMPTaskwaitDirective(const OMPTaskwaitDirective &S) { 3767 CGM.getOpenMPRuntime().emitTaskwaitCall(*this, S.getBeginLoc()); 3768 } 3769 3770 void CodeGenFunction::EmitOMPTaskgroupDirective( 3771 const OMPTaskgroupDirective &S) { 3772 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 3773 Action.Enter(CGF); 3774 if (const Expr *E = S.getReductionRef()) { 3775 SmallVector<const Expr *, 4> LHSs; 3776 SmallVector<const Expr *, 4> RHSs; 3777 OMPTaskDataTy Data; 3778 for (const auto *C : S.getClausesOfKind<OMPTaskReductionClause>()) { 3779 auto IPriv = C->privates().begin(); 3780 auto IRed = C->reduction_ops().begin(); 3781 auto ILHS = C->lhs_exprs().begin(); 3782 auto IRHS = C->rhs_exprs().begin(); 3783 for (const Expr *Ref : C->varlists()) { 3784 Data.ReductionVars.emplace_back(Ref); 3785 Data.ReductionCopies.emplace_back(*IPriv); 3786 Data.ReductionOps.emplace_back(*IRed); 3787 LHSs.emplace_back(*ILHS); 3788 RHSs.emplace_back(*IRHS); 3789 std::advance(IPriv, 1); 3790 std::advance(IRed, 1); 3791 std::advance(ILHS, 1); 3792 std::advance(IRHS, 1); 3793 } 3794 } 3795 llvm::Value *ReductionDesc = 3796 CGF.CGM.getOpenMPRuntime().emitTaskReductionInit(CGF, S.getBeginLoc(), 3797 LHSs, RHSs, Data); 3798 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 3799 CGF.EmitVarDecl(*VD); 3800 CGF.EmitStoreOfScalar(ReductionDesc, CGF.GetAddrOfLocalVar(VD), 3801 /*Volatile=*/false, E->getType()); 3802 } 3803 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 3804 }; 3805 OMPLexicalScope Scope(*this, S, OMPD_unknown); 3806 CGM.getOpenMPRuntime().emitTaskgroupRegion(*this, CodeGen, S.getBeginLoc()); 3807 } 3808 3809 void CodeGenFunction::EmitOMPFlushDirective(const OMPFlushDirective &S) { 3810 llvm::AtomicOrdering AO = S.getSingleClause<OMPFlushClause>() 3811 ? llvm::AtomicOrdering::NotAtomic 3812 : llvm::AtomicOrdering::AcquireRelease; 3813 CGM.getOpenMPRuntime().emitFlush( 3814 *this, 3815 [&S]() -> ArrayRef<const Expr *> { 3816 if (const auto *FlushClause = S.getSingleClause<OMPFlushClause>()) 3817 return llvm::makeArrayRef(FlushClause->varlist_begin(), 3818 FlushClause->varlist_end()); 3819 return llvm::None; 3820 }(), 3821 S.getBeginLoc(), AO); 3822 } 3823 3824 void CodeGenFunction::EmitOMPDepobjDirective(const OMPDepobjDirective &S) { 3825 const auto *DO = S.getSingleClause<OMPDepobjClause>(); 3826 LValue DOLVal = EmitLValue(DO->getDepobj()); 3827 if (const auto *DC = S.getSingleClause<OMPDependClause>()) { 3828 OMPTaskDataTy::DependData Dependencies(DC->getDependencyKind(), 3829 DC->getModifier()); 3830 Dependencies.DepExprs.append(DC->varlist_begin(), DC->varlist_end()); 3831 Address DepAddr = CGM.getOpenMPRuntime().emitDepobjDependClause( 3832 *this, Dependencies, DC->getBeginLoc()); 3833 EmitStoreOfScalar(DepAddr.getPointer(), DOLVal); 3834 return; 3835 } 3836 if (const auto *DC = S.getSingleClause<OMPDestroyClause>()) { 3837 CGM.getOpenMPRuntime().emitDestroyClause(*this, DOLVal, DC->getBeginLoc()); 3838 return; 3839 } 3840 if (const auto *UC = S.getSingleClause<OMPUpdateClause>()) { 3841 CGM.getOpenMPRuntime().emitUpdateClause( 3842 *this, DOLVal, UC->getDependencyKind(), UC->getBeginLoc()); 3843 return; 3844 } 3845 } 3846 3847 void CodeGenFunction::EmitOMPDistributeLoop(const OMPLoopDirective &S, 3848 const CodeGenLoopTy &CodeGenLoop, 3849 Expr *IncExpr) { 3850 // Emit the loop iteration variable. 3851 const auto *IVExpr = cast<DeclRefExpr>(S.getIterationVariable()); 3852 const auto *IVDecl = cast<VarDecl>(IVExpr->getDecl()); 3853 EmitVarDecl(*IVDecl); 3854 3855 // Emit the iterations count variable. 3856 // If it is not a variable, Sema decided to calculate iterations count on each 3857 // iteration (e.g., it is foldable into a constant). 3858 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 3859 EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 3860 // Emit calculation of the iterations count. 3861 EmitIgnoredExpr(S.getCalcLastIteration()); 3862 } 3863 3864 CGOpenMPRuntime &RT = CGM.getOpenMPRuntime(); 3865 3866 bool HasLastprivateClause = false; 3867 // Check pre-condition. 3868 { 3869 OMPLoopScope PreInitScope(*this, S); 3870 // Skip the entire loop if we don't meet the precondition. 3871 // If the condition constant folds and can be elided, avoid emitting the 3872 // whole loop. 3873 bool CondConstant; 3874 llvm::BasicBlock *ContBlock = nullptr; 3875 if (ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 3876 if (!CondConstant) 3877 return; 3878 } else { 3879 llvm::BasicBlock *ThenBlock = createBasicBlock("omp.precond.then"); 3880 ContBlock = createBasicBlock("omp.precond.end"); 3881 emitPreCond(*this, S, S.getPreCond(), ThenBlock, ContBlock, 3882 getProfileCount(&S)); 3883 EmitBlock(ThenBlock); 3884 incrementProfileCounter(&S); 3885 } 3886 3887 emitAlignedClause(*this, S); 3888 // Emit 'then' code. 3889 { 3890 // Emit helper vars inits. 3891 3892 LValue LB = EmitOMPHelperVar( 3893 *this, cast<DeclRefExpr>( 3894 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3895 ? S.getCombinedLowerBoundVariable() 3896 : S.getLowerBoundVariable()))); 3897 LValue UB = EmitOMPHelperVar( 3898 *this, cast<DeclRefExpr>( 3899 (isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3900 ? S.getCombinedUpperBoundVariable() 3901 : S.getUpperBoundVariable()))); 3902 LValue ST = 3903 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getStrideVariable())); 3904 LValue IL = 3905 EmitOMPHelperVar(*this, cast<DeclRefExpr>(S.getIsLastIterVariable())); 3906 3907 OMPPrivateScope LoopScope(*this); 3908 if (EmitOMPFirstprivateClause(S, LoopScope)) { 3909 // Emit implicit barrier to synchronize threads and avoid data races 3910 // on initialization of firstprivate variables and post-update of 3911 // lastprivate variables. 3912 CGM.getOpenMPRuntime().emitBarrierCall( 3913 *this, S.getBeginLoc(), OMPD_unknown, /*EmitChecks=*/false, 3914 /*ForceSimpleCall=*/true); 3915 } 3916 EmitOMPPrivateClause(S, LoopScope); 3917 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 3918 !isOpenMPParallelDirective(S.getDirectiveKind()) && 3919 !isOpenMPTeamsDirective(S.getDirectiveKind())) 3920 EmitOMPReductionClauseInit(S, LoopScope); 3921 HasLastprivateClause = EmitOMPLastprivateClauseInit(S, LoopScope); 3922 EmitOMPPrivateLoopCounters(S, LoopScope); 3923 (void)LoopScope.Privatize(); 3924 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 3925 CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(*this, S); 3926 3927 // Detect the distribute schedule kind and chunk. 3928 llvm::Value *Chunk = nullptr; 3929 OpenMPDistScheduleClauseKind ScheduleKind = OMPC_DIST_SCHEDULE_unknown; 3930 if (const auto *C = S.getSingleClause<OMPDistScheduleClause>()) { 3931 ScheduleKind = C->getDistScheduleKind(); 3932 if (const Expr *Ch = C->getChunkSize()) { 3933 Chunk = EmitScalarExpr(Ch); 3934 Chunk = EmitScalarConversion(Chunk, Ch->getType(), 3935 S.getIterationVariable()->getType(), 3936 S.getBeginLoc()); 3937 } 3938 } else { 3939 // Default behaviour for dist_schedule clause. 3940 CGM.getOpenMPRuntime().getDefaultDistScheduleAndChunk( 3941 *this, S, ScheduleKind, Chunk); 3942 } 3943 const unsigned IVSize = getContext().getTypeSize(IVExpr->getType()); 3944 const bool IVSigned = IVExpr->getType()->hasSignedIntegerRepresentation(); 3945 3946 // OpenMP [2.10.8, distribute Construct, Description] 3947 // If dist_schedule is specified, kind must be static. If specified, 3948 // iterations are divided into chunks of size chunk_size, chunks are 3949 // assigned to the teams of the league in a round-robin fashion in the 3950 // order of the team number. When no chunk_size is specified, the 3951 // iteration space is divided into chunks that are approximately equal 3952 // in size, and at most one chunk is distributed to each team of the 3953 // league. The size of the chunks is unspecified in this case. 3954 bool StaticChunked = RT.isStaticChunked( 3955 ScheduleKind, /* Chunked */ Chunk != nullptr) && 3956 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()); 3957 if (RT.isStaticNonchunked(ScheduleKind, 3958 /* Chunked */ Chunk != nullptr) || 3959 StaticChunked) { 3960 CGOpenMPRuntime::StaticRTInput StaticInit( 3961 IVSize, IVSigned, /* Ordered = */ false, IL.getAddress(*this), 3962 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 3963 StaticChunked ? Chunk : nullptr); 3964 RT.emitDistributeStaticInit(*this, S.getBeginLoc(), ScheduleKind, 3965 StaticInit); 3966 JumpDest LoopExit = 3967 getJumpDestInCurrentScope(createBasicBlock("omp.loop.exit")); 3968 // UB = min(UB, GlobalUB); 3969 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3970 ? S.getCombinedEnsureUpperBound() 3971 : S.getEnsureUpperBound()); 3972 // IV = LB; 3973 EmitIgnoredExpr(isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3974 ? S.getCombinedInit() 3975 : S.getInit()); 3976 3977 const Expr *Cond = 3978 isOpenMPLoopBoundSharingDirective(S.getDirectiveKind()) 3979 ? S.getCombinedCond() 3980 : S.getCond(); 3981 3982 if (StaticChunked) 3983 Cond = S.getCombinedDistCond(); 3984 3985 // For static unchunked schedules generate: 3986 // 3987 // 1. For distribute alone, codegen 3988 // while (idx <= UB) { 3989 // BODY; 3990 // ++idx; 3991 // } 3992 // 3993 // 2. When combined with 'for' (e.g. as in 'distribute parallel for') 3994 // while (idx <= UB) { 3995 // <CodeGen rest of pragma>(LB, UB); 3996 // idx += ST; 3997 // } 3998 // 3999 // For static chunk one schedule generate: 4000 // 4001 // while (IV <= GlobalUB) { 4002 // <CodeGen rest of pragma>(LB, UB); 4003 // LB += ST; 4004 // UB += ST; 4005 // UB = min(UB, GlobalUB); 4006 // IV = LB; 4007 // } 4008 // 4009 emitCommonSimdLoop( 4010 *this, S, 4011 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4012 if (isOpenMPSimdDirective(S.getDirectiveKind())) 4013 CGF.EmitOMPSimdInit(S, /*IsMonotonic=*/true); 4014 }, 4015 [&S, &LoopScope, Cond, IncExpr, LoopExit, &CodeGenLoop, 4016 StaticChunked](CodeGenFunction &CGF, PrePostActionTy &) { 4017 CGF.EmitOMPInnerLoop( 4018 S, LoopScope.requiresCleanups(), Cond, IncExpr, 4019 [&S, LoopExit, &CodeGenLoop](CodeGenFunction &CGF) { 4020 CodeGenLoop(CGF, S, LoopExit); 4021 }, 4022 [&S, StaticChunked](CodeGenFunction &CGF) { 4023 if (StaticChunked) { 4024 CGF.EmitIgnoredExpr(S.getCombinedNextLowerBound()); 4025 CGF.EmitIgnoredExpr(S.getCombinedNextUpperBound()); 4026 CGF.EmitIgnoredExpr(S.getCombinedEnsureUpperBound()); 4027 CGF.EmitIgnoredExpr(S.getCombinedInit()); 4028 } 4029 }); 4030 }); 4031 EmitBlock(LoopExit.getBlock()); 4032 // Tell the runtime we are done. 4033 RT.emitForStaticFinish(*this, S.getEndLoc(), S.getDirectiveKind()); 4034 } else { 4035 // Emit the outer loop, which requests its work chunk [LB..UB] from 4036 // runtime and runs the inner loop to process it. 4037 const OMPLoopArguments LoopArguments = { 4038 LB.getAddress(*this), UB.getAddress(*this), ST.getAddress(*this), 4039 IL.getAddress(*this), Chunk}; 4040 EmitOMPDistributeOuterLoop(ScheduleKind, S, LoopScope, LoopArguments, 4041 CodeGenLoop); 4042 } 4043 if (isOpenMPSimdDirective(S.getDirectiveKind())) { 4044 EmitOMPSimdFinal(S, [IL, &S](CodeGenFunction &CGF) { 4045 return CGF.Builder.CreateIsNotNull( 4046 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 4047 }); 4048 } 4049 if (isOpenMPSimdDirective(S.getDirectiveKind()) && 4050 !isOpenMPParallelDirective(S.getDirectiveKind()) && 4051 !isOpenMPTeamsDirective(S.getDirectiveKind())) { 4052 EmitOMPReductionClauseFinal(S, OMPD_simd); 4053 // Emit post-update of the reduction variables if IsLastIter != 0. 4054 emitPostUpdateForReductionClause( 4055 *this, S, [IL, &S](CodeGenFunction &CGF) { 4056 return CGF.Builder.CreateIsNotNull( 4057 CGF.EmitLoadOfScalar(IL, S.getBeginLoc())); 4058 }); 4059 } 4060 // Emit final copy of the lastprivate variables if IsLastIter != 0. 4061 if (HasLastprivateClause) { 4062 EmitOMPLastprivateClauseFinal( 4063 S, /*NoFinals=*/false, 4064 Builder.CreateIsNotNull(EmitLoadOfScalar(IL, S.getBeginLoc()))); 4065 } 4066 } 4067 4068 // We're now done with the loop, so jump to the continuation block. 4069 if (ContBlock) { 4070 EmitBranch(ContBlock); 4071 EmitBlock(ContBlock, true); 4072 } 4073 } 4074 } 4075 4076 void CodeGenFunction::EmitOMPDistributeDirective( 4077 const OMPDistributeDirective &S) { 4078 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4079 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4080 }; 4081 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4082 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_distribute, CodeGen); 4083 } 4084 4085 static llvm::Function *emitOutlinedOrderedFunction(CodeGenModule &CGM, 4086 const CapturedStmt *S, 4087 SourceLocation Loc) { 4088 CodeGenFunction CGF(CGM, /*suppressNewContext=*/true); 4089 CodeGenFunction::CGCapturedStmtInfo CapStmtInfo; 4090 CGF.CapturedStmtInfo = &CapStmtInfo; 4091 llvm::Function *Fn = CGF.GenerateOpenMPCapturedStmtFunction(*S, Loc); 4092 Fn->setDoesNotRecurse(); 4093 return Fn; 4094 } 4095 4096 void CodeGenFunction::EmitOMPOrderedDirective(const OMPOrderedDirective &S) { 4097 if (S.hasClausesOfKind<OMPDependClause>()) { 4098 assert(!S.getAssociatedStmt() && 4099 "No associated statement must be in ordered depend construct."); 4100 for (const auto *DC : S.getClausesOfKind<OMPDependClause>()) 4101 CGM.getOpenMPRuntime().emitDoacrossOrdered(*this, DC); 4102 return; 4103 } 4104 const auto *C = S.getSingleClause<OMPSIMDClause>(); 4105 auto &&CodeGen = [&S, C, this](CodeGenFunction &CGF, 4106 PrePostActionTy &Action) { 4107 const CapturedStmt *CS = S.getInnermostCapturedStmt(); 4108 if (C) { 4109 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 4110 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 4111 llvm::Function *OutlinedFn = 4112 emitOutlinedOrderedFunction(CGM, CS, S.getBeginLoc()); 4113 CGM.getOpenMPRuntime().emitOutlinedFunctionCall(CGF, S.getBeginLoc(), 4114 OutlinedFn, CapturedVars); 4115 } else { 4116 Action.Enter(CGF); 4117 CGF.EmitStmt(CS->getCapturedStmt()); 4118 } 4119 }; 4120 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4121 CGM.getOpenMPRuntime().emitOrderedRegion(*this, CodeGen, S.getBeginLoc(), !C); 4122 } 4123 4124 static llvm::Value *convertToScalarValue(CodeGenFunction &CGF, RValue Val, 4125 QualType SrcType, QualType DestType, 4126 SourceLocation Loc) { 4127 assert(CGF.hasScalarEvaluationKind(DestType) && 4128 "DestType must have scalar evaluation kind."); 4129 assert(!Val.isAggregate() && "Must be a scalar or complex."); 4130 return Val.isScalar() ? CGF.EmitScalarConversion(Val.getScalarVal(), SrcType, 4131 DestType, Loc) 4132 : CGF.EmitComplexToScalarConversion( 4133 Val.getComplexVal(), SrcType, DestType, Loc); 4134 } 4135 4136 static CodeGenFunction::ComplexPairTy 4137 convertToComplexValue(CodeGenFunction &CGF, RValue Val, QualType SrcType, 4138 QualType DestType, SourceLocation Loc) { 4139 assert(CGF.getEvaluationKind(DestType) == TEK_Complex && 4140 "DestType must have complex evaluation kind."); 4141 CodeGenFunction::ComplexPairTy ComplexVal; 4142 if (Val.isScalar()) { 4143 // Convert the input element to the element type of the complex. 4144 QualType DestElementType = 4145 DestType->castAs<ComplexType>()->getElementType(); 4146 llvm::Value *ScalarVal = CGF.EmitScalarConversion( 4147 Val.getScalarVal(), SrcType, DestElementType, Loc); 4148 ComplexVal = CodeGenFunction::ComplexPairTy( 4149 ScalarVal, llvm::Constant::getNullValue(ScalarVal->getType())); 4150 } else { 4151 assert(Val.isComplex() && "Must be a scalar or complex."); 4152 QualType SrcElementType = SrcType->castAs<ComplexType>()->getElementType(); 4153 QualType DestElementType = 4154 DestType->castAs<ComplexType>()->getElementType(); 4155 ComplexVal.first = CGF.EmitScalarConversion( 4156 Val.getComplexVal().first, SrcElementType, DestElementType, Loc); 4157 ComplexVal.second = CGF.EmitScalarConversion( 4158 Val.getComplexVal().second, SrcElementType, DestElementType, Loc); 4159 } 4160 return ComplexVal; 4161 } 4162 4163 static void emitSimpleAtomicStore(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 4164 LValue LVal, RValue RVal) { 4165 if (LVal.isGlobalReg()) 4166 CGF.EmitStoreThroughGlobalRegLValue(RVal, LVal); 4167 else 4168 CGF.EmitAtomicStore(RVal, LVal, AO, LVal.isVolatile(), /*isInit=*/false); 4169 } 4170 4171 static RValue emitSimpleAtomicLoad(CodeGenFunction &CGF, 4172 llvm::AtomicOrdering AO, LValue LVal, 4173 SourceLocation Loc) { 4174 if (LVal.isGlobalReg()) 4175 return CGF.EmitLoadOfLValue(LVal, Loc); 4176 return CGF.EmitAtomicLoad( 4177 LVal, Loc, llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO), 4178 LVal.isVolatile()); 4179 } 4180 4181 void CodeGenFunction::emitOMPSimpleStore(LValue LVal, RValue RVal, 4182 QualType RValTy, SourceLocation Loc) { 4183 switch (getEvaluationKind(LVal.getType())) { 4184 case TEK_Scalar: 4185 EmitStoreThroughLValue(RValue::get(convertToScalarValue( 4186 *this, RVal, RValTy, LVal.getType(), Loc)), 4187 LVal); 4188 break; 4189 case TEK_Complex: 4190 EmitStoreOfComplex( 4191 convertToComplexValue(*this, RVal, RValTy, LVal.getType(), Loc), LVal, 4192 /*isInit=*/false); 4193 break; 4194 case TEK_Aggregate: 4195 llvm_unreachable("Must be a scalar or complex."); 4196 } 4197 } 4198 4199 static void emitOMPAtomicReadExpr(CodeGenFunction &CGF, llvm::AtomicOrdering AO, 4200 const Expr *X, const Expr *V, 4201 SourceLocation Loc) { 4202 // v = x; 4203 assert(V->isLValue() && "V of 'omp atomic read' is not lvalue"); 4204 assert(X->isLValue() && "X of 'omp atomic read' is not lvalue"); 4205 LValue XLValue = CGF.EmitLValue(X); 4206 LValue VLValue = CGF.EmitLValue(V); 4207 RValue Res = emitSimpleAtomicLoad(CGF, AO, XLValue, Loc); 4208 // OpenMP, 2.17.7, atomic Construct 4209 // If the read or capture clause is specified and the acquire, acq_rel, or 4210 // seq_cst clause is specified then the strong flush on exit from the atomic 4211 // operation is also an acquire flush. 4212 switch (AO) { 4213 case llvm::AtomicOrdering::Acquire: 4214 case llvm::AtomicOrdering::AcquireRelease: 4215 case llvm::AtomicOrdering::SequentiallyConsistent: 4216 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4217 llvm::AtomicOrdering::Acquire); 4218 break; 4219 case llvm::AtomicOrdering::Monotonic: 4220 case llvm::AtomicOrdering::Release: 4221 break; 4222 case llvm::AtomicOrdering::NotAtomic: 4223 case llvm::AtomicOrdering::Unordered: 4224 llvm_unreachable("Unexpected ordering."); 4225 } 4226 CGF.emitOMPSimpleStore(VLValue, Res, X->getType().getNonReferenceType(), Loc); 4227 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 4228 } 4229 4230 static void emitOMPAtomicWriteExpr(CodeGenFunction &CGF, 4231 llvm::AtomicOrdering AO, const Expr *X, 4232 const Expr *E, SourceLocation Loc) { 4233 // x = expr; 4234 assert(X->isLValue() && "X of 'omp atomic write' is not lvalue"); 4235 emitSimpleAtomicStore(CGF, AO, CGF.EmitLValue(X), CGF.EmitAnyExpr(E)); 4236 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4237 // OpenMP, 2.17.7, atomic Construct 4238 // If the write, update, or capture clause is specified and the release, 4239 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4240 // the atomic operation is also a release flush. 4241 switch (AO) { 4242 case llvm::AtomicOrdering::Release: 4243 case llvm::AtomicOrdering::AcquireRelease: 4244 case llvm::AtomicOrdering::SequentiallyConsistent: 4245 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4246 llvm::AtomicOrdering::Release); 4247 break; 4248 case llvm::AtomicOrdering::Acquire: 4249 case llvm::AtomicOrdering::Monotonic: 4250 break; 4251 case llvm::AtomicOrdering::NotAtomic: 4252 case llvm::AtomicOrdering::Unordered: 4253 llvm_unreachable("Unexpected ordering."); 4254 } 4255 } 4256 4257 static std::pair<bool, RValue> emitOMPAtomicRMW(CodeGenFunction &CGF, LValue X, 4258 RValue Update, 4259 BinaryOperatorKind BO, 4260 llvm::AtomicOrdering AO, 4261 bool IsXLHSInRHSPart) { 4262 ASTContext &Context = CGF.getContext(); 4263 // Allow atomicrmw only if 'x' and 'update' are integer values, lvalue for 'x' 4264 // expression is simple and atomic is allowed for the given type for the 4265 // target platform. 4266 if (BO == BO_Comma || !Update.isScalar() || 4267 !Update.getScalarVal()->getType()->isIntegerTy() || !X.isSimple() || 4268 (!isa<llvm::ConstantInt>(Update.getScalarVal()) && 4269 (Update.getScalarVal()->getType() != 4270 X.getAddress(CGF).getElementType())) || 4271 !X.getAddress(CGF).getElementType()->isIntegerTy() || 4272 !Context.getTargetInfo().hasBuiltinAtomic( 4273 Context.getTypeSize(X.getType()), Context.toBits(X.getAlignment()))) 4274 return std::make_pair(false, RValue::get(nullptr)); 4275 4276 llvm::AtomicRMWInst::BinOp RMWOp; 4277 switch (BO) { 4278 case BO_Add: 4279 RMWOp = llvm::AtomicRMWInst::Add; 4280 break; 4281 case BO_Sub: 4282 if (!IsXLHSInRHSPart) 4283 return std::make_pair(false, RValue::get(nullptr)); 4284 RMWOp = llvm::AtomicRMWInst::Sub; 4285 break; 4286 case BO_And: 4287 RMWOp = llvm::AtomicRMWInst::And; 4288 break; 4289 case BO_Or: 4290 RMWOp = llvm::AtomicRMWInst::Or; 4291 break; 4292 case BO_Xor: 4293 RMWOp = llvm::AtomicRMWInst::Xor; 4294 break; 4295 case BO_LT: 4296 RMWOp = X.getType()->hasSignedIntegerRepresentation() 4297 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Min 4298 : llvm::AtomicRMWInst::Max) 4299 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMin 4300 : llvm::AtomicRMWInst::UMax); 4301 break; 4302 case BO_GT: 4303 RMWOp = X.getType()->hasSignedIntegerRepresentation() 4304 ? (IsXLHSInRHSPart ? llvm::AtomicRMWInst::Max 4305 : llvm::AtomicRMWInst::Min) 4306 : (IsXLHSInRHSPart ? llvm::AtomicRMWInst::UMax 4307 : llvm::AtomicRMWInst::UMin); 4308 break; 4309 case BO_Assign: 4310 RMWOp = llvm::AtomicRMWInst::Xchg; 4311 break; 4312 case BO_Mul: 4313 case BO_Div: 4314 case BO_Rem: 4315 case BO_Shl: 4316 case BO_Shr: 4317 case BO_LAnd: 4318 case BO_LOr: 4319 return std::make_pair(false, RValue::get(nullptr)); 4320 case BO_PtrMemD: 4321 case BO_PtrMemI: 4322 case BO_LE: 4323 case BO_GE: 4324 case BO_EQ: 4325 case BO_NE: 4326 case BO_Cmp: 4327 case BO_AddAssign: 4328 case BO_SubAssign: 4329 case BO_AndAssign: 4330 case BO_OrAssign: 4331 case BO_XorAssign: 4332 case BO_MulAssign: 4333 case BO_DivAssign: 4334 case BO_RemAssign: 4335 case BO_ShlAssign: 4336 case BO_ShrAssign: 4337 case BO_Comma: 4338 llvm_unreachable("Unsupported atomic update operation"); 4339 } 4340 llvm::Value *UpdateVal = Update.getScalarVal(); 4341 if (auto *IC = dyn_cast<llvm::ConstantInt>(UpdateVal)) { 4342 UpdateVal = CGF.Builder.CreateIntCast( 4343 IC, X.getAddress(CGF).getElementType(), 4344 X.getType()->hasSignedIntegerRepresentation()); 4345 } 4346 llvm::Value *Res = 4347 CGF.Builder.CreateAtomicRMW(RMWOp, X.getPointer(CGF), UpdateVal, AO); 4348 return std::make_pair(true, RValue::get(Res)); 4349 } 4350 4351 std::pair<bool, RValue> CodeGenFunction::EmitOMPAtomicSimpleUpdateExpr( 4352 LValue X, RValue E, BinaryOperatorKind BO, bool IsXLHSInRHSPart, 4353 llvm::AtomicOrdering AO, SourceLocation Loc, 4354 const llvm::function_ref<RValue(RValue)> CommonGen) { 4355 // Update expressions are allowed to have the following forms: 4356 // x binop= expr; -> xrval + expr; 4357 // x++, ++x -> xrval + 1; 4358 // x--, --x -> xrval - 1; 4359 // x = x binop expr; -> xrval binop expr 4360 // x = expr Op x; - > expr binop xrval; 4361 auto Res = emitOMPAtomicRMW(*this, X, E, BO, AO, IsXLHSInRHSPart); 4362 if (!Res.first) { 4363 if (X.isGlobalReg()) { 4364 // Emit an update expression: 'xrval' binop 'expr' or 'expr' binop 4365 // 'xrval'. 4366 EmitStoreThroughLValue(CommonGen(EmitLoadOfLValue(X, Loc)), X); 4367 } else { 4368 // Perform compare-and-swap procedure. 4369 EmitAtomicUpdate(X, AO, CommonGen, X.getType().isVolatileQualified()); 4370 } 4371 } 4372 return Res; 4373 } 4374 4375 static void emitOMPAtomicUpdateExpr(CodeGenFunction &CGF, 4376 llvm::AtomicOrdering AO, const Expr *X, 4377 const Expr *E, const Expr *UE, 4378 bool IsXLHSInRHSPart, SourceLocation Loc) { 4379 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 4380 "Update expr in 'atomic update' must be a binary operator."); 4381 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 4382 // Update expressions are allowed to have the following forms: 4383 // x binop= expr; -> xrval + expr; 4384 // x++, ++x -> xrval + 1; 4385 // x--, --x -> xrval - 1; 4386 // x = x binop expr; -> xrval binop expr 4387 // x = expr Op x; - > expr binop xrval; 4388 assert(X->isLValue() && "X of 'omp atomic update' is not lvalue"); 4389 LValue XLValue = CGF.EmitLValue(X); 4390 RValue ExprRValue = CGF.EmitAnyExpr(E); 4391 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 4392 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 4393 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 4394 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 4395 auto &&Gen = [&CGF, UE, ExprRValue, XRValExpr, ERValExpr](RValue XRValue) { 4396 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4397 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 4398 return CGF.EmitAnyExpr(UE); 4399 }; 4400 (void)CGF.EmitOMPAtomicSimpleUpdateExpr( 4401 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 4402 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4403 // OpenMP, 2.17.7, atomic Construct 4404 // If the write, update, or capture clause is specified and the release, 4405 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4406 // the atomic operation is also a release flush. 4407 switch (AO) { 4408 case llvm::AtomicOrdering::Release: 4409 case llvm::AtomicOrdering::AcquireRelease: 4410 case llvm::AtomicOrdering::SequentiallyConsistent: 4411 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4412 llvm::AtomicOrdering::Release); 4413 break; 4414 case llvm::AtomicOrdering::Acquire: 4415 case llvm::AtomicOrdering::Monotonic: 4416 break; 4417 case llvm::AtomicOrdering::NotAtomic: 4418 case llvm::AtomicOrdering::Unordered: 4419 llvm_unreachable("Unexpected ordering."); 4420 } 4421 } 4422 4423 static RValue convertToType(CodeGenFunction &CGF, RValue Value, 4424 QualType SourceType, QualType ResType, 4425 SourceLocation Loc) { 4426 switch (CGF.getEvaluationKind(ResType)) { 4427 case TEK_Scalar: 4428 return RValue::get( 4429 convertToScalarValue(CGF, Value, SourceType, ResType, Loc)); 4430 case TEK_Complex: { 4431 auto Res = convertToComplexValue(CGF, Value, SourceType, ResType, Loc); 4432 return RValue::getComplex(Res.first, Res.second); 4433 } 4434 case TEK_Aggregate: 4435 break; 4436 } 4437 llvm_unreachable("Must be a scalar or complex."); 4438 } 4439 4440 static void emitOMPAtomicCaptureExpr(CodeGenFunction &CGF, 4441 llvm::AtomicOrdering AO, 4442 bool IsPostfixUpdate, const Expr *V, 4443 const Expr *X, const Expr *E, 4444 const Expr *UE, bool IsXLHSInRHSPart, 4445 SourceLocation Loc) { 4446 assert(X->isLValue() && "X of 'omp atomic capture' is not lvalue"); 4447 assert(V->isLValue() && "V of 'omp atomic capture' is not lvalue"); 4448 RValue NewVVal; 4449 LValue VLValue = CGF.EmitLValue(V); 4450 LValue XLValue = CGF.EmitLValue(X); 4451 RValue ExprRValue = CGF.EmitAnyExpr(E); 4452 QualType NewVValType; 4453 if (UE) { 4454 // 'x' is updated with some additional value. 4455 assert(isa<BinaryOperator>(UE->IgnoreImpCasts()) && 4456 "Update expr in 'atomic capture' must be a binary operator."); 4457 const auto *BOUE = cast<BinaryOperator>(UE->IgnoreImpCasts()); 4458 // Update expressions are allowed to have the following forms: 4459 // x binop= expr; -> xrval + expr; 4460 // x++, ++x -> xrval + 1; 4461 // x--, --x -> xrval - 1; 4462 // x = x binop expr; -> xrval binop expr 4463 // x = expr Op x; - > expr binop xrval; 4464 const auto *LHS = cast<OpaqueValueExpr>(BOUE->getLHS()->IgnoreImpCasts()); 4465 const auto *RHS = cast<OpaqueValueExpr>(BOUE->getRHS()->IgnoreImpCasts()); 4466 const OpaqueValueExpr *XRValExpr = IsXLHSInRHSPart ? LHS : RHS; 4467 NewVValType = XRValExpr->getType(); 4468 const OpaqueValueExpr *ERValExpr = IsXLHSInRHSPart ? RHS : LHS; 4469 auto &&Gen = [&CGF, &NewVVal, UE, ExprRValue, XRValExpr, ERValExpr, 4470 IsPostfixUpdate](RValue XRValue) { 4471 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4472 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, XRValue); 4473 RValue Res = CGF.EmitAnyExpr(UE); 4474 NewVVal = IsPostfixUpdate ? XRValue : Res; 4475 return Res; 4476 }; 4477 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 4478 XLValue, ExprRValue, BOUE->getOpcode(), IsXLHSInRHSPart, AO, Loc, Gen); 4479 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4480 if (Res.first) { 4481 // 'atomicrmw' instruction was generated. 4482 if (IsPostfixUpdate) { 4483 // Use old value from 'atomicrmw'. 4484 NewVVal = Res.second; 4485 } else { 4486 // 'atomicrmw' does not provide new value, so evaluate it using old 4487 // value of 'x'. 4488 CodeGenFunction::OpaqueValueMapping MapExpr(CGF, ERValExpr, ExprRValue); 4489 CodeGenFunction::OpaqueValueMapping MapX(CGF, XRValExpr, Res.second); 4490 NewVVal = CGF.EmitAnyExpr(UE); 4491 } 4492 } 4493 } else { 4494 // 'x' is simply rewritten with some 'expr'. 4495 NewVValType = X->getType().getNonReferenceType(); 4496 ExprRValue = convertToType(CGF, ExprRValue, E->getType(), 4497 X->getType().getNonReferenceType(), Loc); 4498 auto &&Gen = [&NewVVal, ExprRValue](RValue XRValue) { 4499 NewVVal = XRValue; 4500 return ExprRValue; 4501 }; 4502 // Try to perform atomicrmw xchg, otherwise simple exchange. 4503 auto Res = CGF.EmitOMPAtomicSimpleUpdateExpr( 4504 XLValue, ExprRValue, /*BO=*/BO_Assign, /*IsXLHSInRHSPart=*/false, AO, 4505 Loc, Gen); 4506 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, X); 4507 if (Res.first) { 4508 // 'atomicrmw' instruction was generated. 4509 NewVVal = IsPostfixUpdate ? Res.second : ExprRValue; 4510 } 4511 } 4512 // Emit post-update store to 'v' of old/new 'x' value. 4513 CGF.emitOMPSimpleStore(VLValue, NewVVal, NewVValType, Loc); 4514 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF, V); 4515 // OpenMP, 2.17.7, atomic Construct 4516 // If the write, update, or capture clause is specified and the release, 4517 // acq_rel, or seq_cst clause is specified then the strong flush on entry to 4518 // the atomic operation is also a release flush. 4519 // If the read or capture clause is specified and the acquire, acq_rel, or 4520 // seq_cst clause is specified then the strong flush on exit from the atomic 4521 // operation is also an acquire flush. 4522 switch (AO) { 4523 case llvm::AtomicOrdering::Release: 4524 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4525 llvm::AtomicOrdering::Release); 4526 break; 4527 case llvm::AtomicOrdering::Acquire: 4528 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4529 llvm::AtomicOrdering::Acquire); 4530 break; 4531 case llvm::AtomicOrdering::AcquireRelease: 4532 case llvm::AtomicOrdering::SequentiallyConsistent: 4533 CGF.CGM.getOpenMPRuntime().emitFlush(CGF, llvm::None, Loc, 4534 llvm::AtomicOrdering::AcquireRelease); 4535 break; 4536 case llvm::AtomicOrdering::Monotonic: 4537 break; 4538 case llvm::AtomicOrdering::NotAtomic: 4539 case llvm::AtomicOrdering::Unordered: 4540 llvm_unreachable("Unexpected ordering."); 4541 } 4542 } 4543 4544 static void emitOMPAtomicExpr(CodeGenFunction &CGF, OpenMPClauseKind Kind, 4545 llvm::AtomicOrdering AO, bool IsPostfixUpdate, 4546 const Expr *X, const Expr *V, const Expr *E, 4547 const Expr *UE, bool IsXLHSInRHSPart, 4548 SourceLocation Loc) { 4549 switch (Kind) { 4550 case OMPC_read: 4551 emitOMPAtomicReadExpr(CGF, AO, X, V, Loc); 4552 break; 4553 case OMPC_write: 4554 emitOMPAtomicWriteExpr(CGF, AO, X, E, Loc); 4555 break; 4556 case OMPC_unknown: 4557 case OMPC_update: 4558 emitOMPAtomicUpdateExpr(CGF, AO, X, E, UE, IsXLHSInRHSPart, Loc); 4559 break; 4560 case OMPC_capture: 4561 emitOMPAtomicCaptureExpr(CGF, AO, IsPostfixUpdate, V, X, E, UE, 4562 IsXLHSInRHSPart, Loc); 4563 break; 4564 case OMPC_if: 4565 case OMPC_final: 4566 case OMPC_num_threads: 4567 case OMPC_private: 4568 case OMPC_firstprivate: 4569 case OMPC_lastprivate: 4570 case OMPC_reduction: 4571 case OMPC_task_reduction: 4572 case OMPC_in_reduction: 4573 case OMPC_safelen: 4574 case OMPC_simdlen: 4575 case OMPC_allocator: 4576 case OMPC_allocate: 4577 case OMPC_collapse: 4578 case OMPC_default: 4579 case OMPC_seq_cst: 4580 case OMPC_acq_rel: 4581 case OMPC_acquire: 4582 case OMPC_release: 4583 case OMPC_relaxed: 4584 case OMPC_shared: 4585 case OMPC_linear: 4586 case OMPC_aligned: 4587 case OMPC_copyin: 4588 case OMPC_copyprivate: 4589 case OMPC_flush: 4590 case OMPC_depobj: 4591 case OMPC_proc_bind: 4592 case OMPC_schedule: 4593 case OMPC_ordered: 4594 case OMPC_nowait: 4595 case OMPC_untied: 4596 case OMPC_threadprivate: 4597 case OMPC_depend: 4598 case OMPC_mergeable: 4599 case OMPC_device: 4600 case OMPC_threads: 4601 case OMPC_simd: 4602 case OMPC_map: 4603 case OMPC_num_teams: 4604 case OMPC_thread_limit: 4605 case OMPC_priority: 4606 case OMPC_grainsize: 4607 case OMPC_nogroup: 4608 case OMPC_num_tasks: 4609 case OMPC_hint: 4610 case OMPC_dist_schedule: 4611 case OMPC_defaultmap: 4612 case OMPC_uniform: 4613 case OMPC_to: 4614 case OMPC_from: 4615 case OMPC_use_device_ptr: 4616 case OMPC_is_device_ptr: 4617 case OMPC_unified_address: 4618 case OMPC_unified_shared_memory: 4619 case OMPC_reverse_offload: 4620 case OMPC_dynamic_allocators: 4621 case OMPC_atomic_default_mem_order: 4622 case OMPC_device_type: 4623 case OMPC_match: 4624 case OMPC_nontemporal: 4625 case OMPC_order: 4626 case OMPC_destroy: 4627 case OMPC_detach: 4628 case OMPC_inclusive: 4629 case OMPC_exclusive: 4630 llvm_unreachable("Clause is not allowed in 'omp atomic'."); 4631 } 4632 } 4633 4634 void CodeGenFunction::EmitOMPAtomicDirective(const OMPAtomicDirective &S) { 4635 llvm::AtomicOrdering AO = llvm::AtomicOrdering::Monotonic; 4636 bool MemOrderingSpecified = false; 4637 if (S.getSingleClause<OMPSeqCstClause>()) { 4638 AO = llvm::AtomicOrdering::SequentiallyConsistent; 4639 MemOrderingSpecified = true; 4640 } else if (S.getSingleClause<OMPAcqRelClause>()) { 4641 AO = llvm::AtomicOrdering::AcquireRelease; 4642 MemOrderingSpecified = true; 4643 } else if (S.getSingleClause<OMPAcquireClause>()) { 4644 AO = llvm::AtomicOrdering::Acquire; 4645 MemOrderingSpecified = true; 4646 } else if (S.getSingleClause<OMPReleaseClause>()) { 4647 AO = llvm::AtomicOrdering::Release; 4648 MemOrderingSpecified = true; 4649 } else if (S.getSingleClause<OMPRelaxedClause>()) { 4650 AO = llvm::AtomicOrdering::Monotonic; 4651 MemOrderingSpecified = true; 4652 } 4653 OpenMPClauseKind Kind = OMPC_unknown; 4654 for (const OMPClause *C : S.clauses()) { 4655 // Find first clause (skip seq_cst|acq_rel|aqcuire|release|relaxed clause, 4656 // if it is first). 4657 if (C->getClauseKind() != OMPC_seq_cst && 4658 C->getClauseKind() != OMPC_acq_rel && 4659 C->getClauseKind() != OMPC_acquire && 4660 C->getClauseKind() != OMPC_release && 4661 C->getClauseKind() != OMPC_relaxed) { 4662 Kind = C->getClauseKind(); 4663 break; 4664 } 4665 } 4666 if (!MemOrderingSpecified) { 4667 llvm::AtomicOrdering DefaultOrder = 4668 CGM.getOpenMPRuntime().getDefaultMemoryOrdering(); 4669 if (DefaultOrder == llvm::AtomicOrdering::Monotonic || 4670 DefaultOrder == llvm::AtomicOrdering::SequentiallyConsistent || 4671 (DefaultOrder == llvm::AtomicOrdering::AcquireRelease && 4672 Kind == OMPC_capture)) { 4673 AO = DefaultOrder; 4674 } else if (DefaultOrder == llvm::AtomicOrdering::AcquireRelease) { 4675 if (Kind == OMPC_unknown || Kind == OMPC_update || Kind == OMPC_write) { 4676 AO = llvm::AtomicOrdering::Release; 4677 } else if (Kind == OMPC_read) { 4678 assert(Kind == OMPC_read && "Unexpected atomic kind."); 4679 AO = llvm::AtomicOrdering::Acquire; 4680 } 4681 } 4682 } 4683 4684 const Stmt *CS = S.getInnermostCapturedStmt()->IgnoreContainers(); 4685 if (const auto *FE = dyn_cast<FullExpr>(CS)) 4686 enterFullExpression(FE); 4687 // Processing for statements under 'atomic capture'. 4688 if (const auto *Compound = dyn_cast<CompoundStmt>(CS)) { 4689 for (const Stmt *C : Compound->body()) { 4690 if (const auto *FE = dyn_cast<FullExpr>(C)) 4691 enterFullExpression(FE); 4692 } 4693 } 4694 4695 auto &&CodeGen = [&S, Kind, AO, CS](CodeGenFunction &CGF, 4696 PrePostActionTy &) { 4697 CGF.EmitStopPoint(CS); 4698 emitOMPAtomicExpr(CGF, Kind, AO, S.isPostfixUpdate(), S.getX(), S.getV(), 4699 S.getExpr(), S.getUpdateExpr(), S.isXLHSInRHSPart(), 4700 S.getBeginLoc()); 4701 }; 4702 OMPLexicalScope Scope(*this, S, OMPD_unknown); 4703 CGM.getOpenMPRuntime().emitInlinedDirective(*this, OMPD_atomic, CodeGen); 4704 } 4705 4706 static void emitCommonOMPTargetDirective(CodeGenFunction &CGF, 4707 const OMPExecutableDirective &S, 4708 const RegionCodeGenTy &CodeGen) { 4709 assert(isOpenMPTargetExecutionDirective(S.getDirectiveKind())); 4710 CodeGenModule &CGM = CGF.CGM; 4711 4712 // On device emit this construct as inlined code. 4713 if (CGM.getLangOpts().OpenMPIsDevice) { 4714 OMPLexicalScope Scope(CGF, S, OMPD_target); 4715 CGM.getOpenMPRuntime().emitInlinedDirective( 4716 CGF, OMPD_target, [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4717 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 4718 }); 4719 return; 4720 } 4721 4722 auto LPCRegion = 4723 CGOpenMPRuntime::LastprivateConditionalRAII::disable(CGF, S); 4724 llvm::Function *Fn = nullptr; 4725 llvm::Constant *FnID = nullptr; 4726 4727 const Expr *IfCond = nullptr; 4728 // Check for the at most one if clause associated with the target region. 4729 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 4730 if (C->getNameModifier() == OMPD_unknown || 4731 C->getNameModifier() == OMPD_target) { 4732 IfCond = C->getCondition(); 4733 break; 4734 } 4735 } 4736 4737 // Check if we have any device clause associated with the directive. 4738 llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device( 4739 nullptr, OMPC_DEVICE_unknown); 4740 if (auto *C = S.getSingleClause<OMPDeviceClause>()) 4741 Device.setPointerAndInt(C->getDevice(), C->getModifier()); 4742 4743 // Check if we have an if clause whose conditional always evaluates to false 4744 // or if we do not have any targets specified. If so the target region is not 4745 // an offload entry point. 4746 bool IsOffloadEntry = true; 4747 if (IfCond) { 4748 bool Val; 4749 if (CGF.ConstantFoldsToSimpleInteger(IfCond, Val) && !Val) 4750 IsOffloadEntry = false; 4751 } 4752 if (CGM.getLangOpts().OMPTargetTriples.empty()) 4753 IsOffloadEntry = false; 4754 4755 assert(CGF.CurFuncDecl && "No parent declaration for target region!"); 4756 StringRef ParentName; 4757 // In case we have Ctors/Dtors we use the complete type variant to produce 4758 // the mangling of the device outlined kernel. 4759 if (const auto *D = dyn_cast<CXXConstructorDecl>(CGF.CurFuncDecl)) 4760 ParentName = CGM.getMangledName(GlobalDecl(D, Ctor_Complete)); 4761 else if (const auto *D = dyn_cast<CXXDestructorDecl>(CGF.CurFuncDecl)) 4762 ParentName = CGM.getMangledName(GlobalDecl(D, Dtor_Complete)); 4763 else 4764 ParentName = 4765 CGM.getMangledName(GlobalDecl(cast<FunctionDecl>(CGF.CurFuncDecl))); 4766 4767 // Emit target region as a standalone region. 4768 CGM.getOpenMPRuntime().emitTargetOutlinedFunction(S, ParentName, Fn, FnID, 4769 IsOffloadEntry, CodeGen); 4770 OMPLexicalScope Scope(CGF, S, OMPD_task); 4771 auto &&SizeEmitter = 4772 [IsOffloadEntry](CodeGenFunction &CGF, 4773 const OMPLoopDirective &D) -> llvm::Value * { 4774 if (IsOffloadEntry) { 4775 OMPLoopScope(CGF, D); 4776 // Emit calculation of the iterations count. 4777 llvm::Value *NumIterations = CGF.EmitScalarExpr(D.getNumIterations()); 4778 NumIterations = CGF.Builder.CreateIntCast(NumIterations, CGF.Int64Ty, 4779 /*isSigned=*/false); 4780 return NumIterations; 4781 } 4782 return nullptr; 4783 }; 4784 CGM.getOpenMPRuntime().emitTargetCall(CGF, S, Fn, FnID, IfCond, Device, 4785 SizeEmitter); 4786 } 4787 4788 static void emitTargetRegion(CodeGenFunction &CGF, const OMPTargetDirective &S, 4789 PrePostActionTy &Action) { 4790 Action.Enter(CGF); 4791 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4792 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4793 CGF.EmitOMPPrivateClause(S, PrivateScope); 4794 (void)PrivateScope.Privatize(); 4795 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 4796 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 4797 4798 CGF.EmitStmt(S.getCapturedStmt(OMPD_target)->getCapturedStmt()); 4799 } 4800 4801 void CodeGenFunction::EmitOMPTargetDeviceFunction(CodeGenModule &CGM, 4802 StringRef ParentName, 4803 const OMPTargetDirective &S) { 4804 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4805 emitTargetRegion(CGF, S, Action); 4806 }; 4807 llvm::Function *Fn; 4808 llvm::Constant *Addr; 4809 // Emit target region as a standalone region. 4810 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4811 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4812 assert(Fn && Addr && "Target device function emission failed."); 4813 } 4814 4815 void CodeGenFunction::EmitOMPTargetDirective(const OMPTargetDirective &S) { 4816 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4817 emitTargetRegion(CGF, S, Action); 4818 }; 4819 emitCommonOMPTargetDirective(*this, S, CodeGen); 4820 } 4821 4822 static void emitCommonOMPTeamsDirective(CodeGenFunction &CGF, 4823 const OMPExecutableDirective &S, 4824 OpenMPDirectiveKind InnermostKind, 4825 const RegionCodeGenTy &CodeGen) { 4826 const CapturedStmt *CS = S.getCapturedStmt(OMPD_teams); 4827 llvm::Function *OutlinedFn = 4828 CGF.CGM.getOpenMPRuntime().emitTeamsOutlinedFunction( 4829 S, *CS->getCapturedDecl()->param_begin(), InnermostKind, CodeGen); 4830 4831 const auto *NT = S.getSingleClause<OMPNumTeamsClause>(); 4832 const auto *TL = S.getSingleClause<OMPThreadLimitClause>(); 4833 if (NT || TL) { 4834 const Expr *NumTeams = NT ? NT->getNumTeams() : nullptr; 4835 const Expr *ThreadLimit = TL ? TL->getThreadLimit() : nullptr; 4836 4837 CGF.CGM.getOpenMPRuntime().emitNumTeamsClause(CGF, NumTeams, ThreadLimit, 4838 S.getBeginLoc()); 4839 } 4840 4841 OMPTeamsScope Scope(CGF, S); 4842 llvm::SmallVector<llvm::Value *, 16> CapturedVars; 4843 CGF.GenerateOpenMPCapturedVars(*CS, CapturedVars); 4844 CGF.CGM.getOpenMPRuntime().emitTeamsCall(CGF, S, S.getBeginLoc(), OutlinedFn, 4845 CapturedVars); 4846 } 4847 4848 void CodeGenFunction::EmitOMPTeamsDirective(const OMPTeamsDirective &S) { 4849 // Emit teams region as a standalone region. 4850 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4851 Action.Enter(CGF); 4852 OMPPrivateScope PrivateScope(CGF); 4853 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4854 CGF.EmitOMPPrivateClause(S, PrivateScope); 4855 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4856 (void)PrivateScope.Privatize(); 4857 CGF.EmitStmt(S.getCapturedStmt(OMPD_teams)->getCapturedStmt()); 4858 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4859 }; 4860 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 4861 emitPostUpdateForReductionClause(*this, S, 4862 [](CodeGenFunction &) { return nullptr; }); 4863 } 4864 4865 static void emitTargetTeamsRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 4866 const OMPTargetTeamsDirective &S) { 4867 auto *CS = S.getCapturedStmt(OMPD_teams); 4868 Action.Enter(CGF); 4869 // Emit teams region as a standalone region. 4870 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 4871 Action.Enter(CGF); 4872 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4873 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 4874 CGF.EmitOMPPrivateClause(S, PrivateScope); 4875 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4876 (void)PrivateScope.Privatize(); 4877 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 4878 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 4879 CGF.EmitStmt(CS->getCapturedStmt()); 4880 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4881 }; 4882 emitCommonOMPTeamsDirective(CGF, S, OMPD_teams, CodeGen); 4883 emitPostUpdateForReductionClause(CGF, S, 4884 [](CodeGenFunction &) { return nullptr; }); 4885 } 4886 4887 void CodeGenFunction::EmitOMPTargetTeamsDeviceFunction( 4888 CodeGenModule &CGM, StringRef ParentName, 4889 const OMPTargetTeamsDirective &S) { 4890 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4891 emitTargetTeamsRegion(CGF, Action, S); 4892 }; 4893 llvm::Function *Fn; 4894 llvm::Constant *Addr; 4895 // Emit target region as a standalone region. 4896 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4897 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4898 assert(Fn && Addr && "Target device function emission failed."); 4899 } 4900 4901 void CodeGenFunction::EmitOMPTargetTeamsDirective( 4902 const OMPTargetTeamsDirective &S) { 4903 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4904 emitTargetTeamsRegion(CGF, Action, S); 4905 }; 4906 emitCommonOMPTargetDirective(*this, S, CodeGen); 4907 } 4908 4909 static void 4910 emitTargetTeamsDistributeRegion(CodeGenFunction &CGF, PrePostActionTy &Action, 4911 const OMPTargetTeamsDistributeDirective &S) { 4912 Action.Enter(CGF); 4913 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4914 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4915 }; 4916 4917 // Emit teams region as a standalone region. 4918 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4919 PrePostActionTy &Action) { 4920 Action.Enter(CGF); 4921 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4922 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4923 (void)PrivateScope.Privatize(); 4924 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4925 CodeGenDistribute); 4926 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4927 }; 4928 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute, CodeGen); 4929 emitPostUpdateForReductionClause(CGF, S, 4930 [](CodeGenFunction &) { return nullptr; }); 4931 } 4932 4933 void CodeGenFunction::EmitOMPTargetTeamsDistributeDeviceFunction( 4934 CodeGenModule &CGM, StringRef ParentName, 4935 const OMPTargetTeamsDistributeDirective &S) { 4936 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4937 emitTargetTeamsDistributeRegion(CGF, Action, S); 4938 }; 4939 llvm::Function *Fn; 4940 llvm::Constant *Addr; 4941 // Emit target region as a standalone region. 4942 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4943 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4944 assert(Fn && Addr && "Target device function emission failed."); 4945 } 4946 4947 void CodeGenFunction::EmitOMPTargetTeamsDistributeDirective( 4948 const OMPTargetTeamsDistributeDirective &S) { 4949 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4950 emitTargetTeamsDistributeRegion(CGF, Action, S); 4951 }; 4952 emitCommonOMPTargetDirective(*this, S, CodeGen); 4953 } 4954 4955 static void emitTargetTeamsDistributeSimdRegion( 4956 CodeGenFunction &CGF, PrePostActionTy &Action, 4957 const OMPTargetTeamsDistributeSimdDirective &S) { 4958 Action.Enter(CGF); 4959 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 4960 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 4961 }; 4962 4963 // Emit teams region as a standalone region. 4964 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 4965 PrePostActionTy &Action) { 4966 Action.Enter(CGF); 4967 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 4968 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 4969 (void)PrivateScope.Privatize(); 4970 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 4971 CodeGenDistribute); 4972 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 4973 }; 4974 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_simd, CodeGen); 4975 emitPostUpdateForReductionClause(CGF, S, 4976 [](CodeGenFunction &) { return nullptr; }); 4977 } 4978 4979 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDeviceFunction( 4980 CodeGenModule &CGM, StringRef ParentName, 4981 const OMPTargetTeamsDistributeSimdDirective &S) { 4982 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4983 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 4984 }; 4985 llvm::Function *Fn; 4986 llvm::Constant *Addr; 4987 // Emit target region as a standalone region. 4988 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 4989 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 4990 assert(Fn && Addr && "Target device function emission failed."); 4991 } 4992 4993 void CodeGenFunction::EmitOMPTargetTeamsDistributeSimdDirective( 4994 const OMPTargetTeamsDistributeSimdDirective &S) { 4995 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 4996 emitTargetTeamsDistributeSimdRegion(CGF, Action, S); 4997 }; 4998 emitCommonOMPTargetDirective(*this, S, CodeGen); 4999 } 5000 5001 void CodeGenFunction::EmitOMPTeamsDistributeDirective( 5002 const OMPTeamsDistributeDirective &S) { 5003 5004 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5005 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5006 }; 5007 5008 // Emit teams region as a standalone region. 5009 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5010 PrePostActionTy &Action) { 5011 Action.Enter(CGF); 5012 OMPPrivateScope PrivateScope(CGF); 5013 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5014 (void)PrivateScope.Privatize(); 5015 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 5016 CodeGenDistribute); 5017 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5018 }; 5019 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute, CodeGen); 5020 emitPostUpdateForReductionClause(*this, S, 5021 [](CodeGenFunction &) { return nullptr; }); 5022 } 5023 5024 void CodeGenFunction::EmitOMPTeamsDistributeSimdDirective( 5025 const OMPTeamsDistributeSimdDirective &S) { 5026 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5027 CGF.EmitOMPDistributeLoop(S, emitOMPLoopBodyWithStopPoint, S.getInc()); 5028 }; 5029 5030 // Emit teams region as a standalone region. 5031 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5032 PrePostActionTy &Action) { 5033 Action.Enter(CGF); 5034 OMPPrivateScope PrivateScope(CGF); 5035 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5036 (void)PrivateScope.Privatize(); 5037 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_simd, 5038 CodeGenDistribute); 5039 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5040 }; 5041 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_simd, CodeGen); 5042 emitPostUpdateForReductionClause(*this, S, 5043 [](CodeGenFunction &) { return nullptr; }); 5044 } 5045 5046 void CodeGenFunction::EmitOMPTeamsDistributeParallelForDirective( 5047 const OMPTeamsDistributeParallelForDirective &S) { 5048 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5049 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5050 S.getDistInc()); 5051 }; 5052 5053 // Emit teams region as a standalone region. 5054 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5055 PrePostActionTy &Action) { 5056 Action.Enter(CGF); 5057 OMPPrivateScope PrivateScope(CGF); 5058 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5059 (void)PrivateScope.Privatize(); 5060 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_distribute, 5061 CodeGenDistribute); 5062 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5063 }; 5064 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for, CodeGen); 5065 emitPostUpdateForReductionClause(*this, S, 5066 [](CodeGenFunction &) { return nullptr; }); 5067 } 5068 5069 void CodeGenFunction::EmitOMPTeamsDistributeParallelForSimdDirective( 5070 const OMPTeamsDistributeParallelForSimdDirective &S) { 5071 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5072 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5073 S.getDistInc()); 5074 }; 5075 5076 // Emit teams region as a standalone region. 5077 auto &&CodeGen = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5078 PrePostActionTy &Action) { 5079 Action.Enter(CGF); 5080 OMPPrivateScope PrivateScope(CGF); 5081 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5082 (void)PrivateScope.Privatize(); 5083 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5084 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5085 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5086 }; 5087 emitCommonOMPTeamsDirective(*this, S, OMPD_distribute_parallel_for_simd, 5088 CodeGen); 5089 emitPostUpdateForReductionClause(*this, S, 5090 [](CodeGenFunction &) { return nullptr; }); 5091 } 5092 5093 static void emitTargetTeamsDistributeParallelForRegion( 5094 CodeGenFunction &CGF, const OMPTargetTeamsDistributeParallelForDirective &S, 5095 PrePostActionTy &Action) { 5096 Action.Enter(CGF); 5097 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5098 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5099 S.getDistInc()); 5100 }; 5101 5102 // Emit teams region as a standalone region. 5103 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5104 PrePostActionTy &Action) { 5105 Action.Enter(CGF); 5106 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5107 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5108 (void)PrivateScope.Privatize(); 5109 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5110 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5111 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5112 }; 5113 5114 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for, 5115 CodeGenTeams); 5116 emitPostUpdateForReductionClause(CGF, S, 5117 [](CodeGenFunction &) { return nullptr; }); 5118 } 5119 5120 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction( 5121 CodeGenModule &CGM, StringRef ParentName, 5122 const OMPTargetTeamsDistributeParallelForDirective &S) { 5123 // Emit SPMD target teams distribute parallel for region as a standalone 5124 // region. 5125 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5126 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 5127 }; 5128 llvm::Function *Fn; 5129 llvm::Constant *Addr; 5130 // Emit target region as a standalone region. 5131 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5132 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5133 assert(Fn && Addr && "Target device function emission failed."); 5134 } 5135 5136 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDirective( 5137 const OMPTargetTeamsDistributeParallelForDirective &S) { 5138 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5139 emitTargetTeamsDistributeParallelForRegion(CGF, S, Action); 5140 }; 5141 emitCommonOMPTargetDirective(*this, S, CodeGen); 5142 } 5143 5144 static void emitTargetTeamsDistributeParallelForSimdRegion( 5145 CodeGenFunction &CGF, 5146 const OMPTargetTeamsDistributeParallelForSimdDirective &S, 5147 PrePostActionTy &Action) { 5148 Action.Enter(CGF); 5149 auto &&CodeGenDistribute = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5150 CGF.EmitOMPDistributeLoop(S, emitInnerParallelForWhenCombined, 5151 S.getDistInc()); 5152 }; 5153 5154 // Emit teams region as a standalone region. 5155 auto &&CodeGenTeams = [&S, &CodeGenDistribute](CodeGenFunction &CGF, 5156 PrePostActionTy &Action) { 5157 Action.Enter(CGF); 5158 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5159 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5160 (void)PrivateScope.Privatize(); 5161 CGF.CGM.getOpenMPRuntime().emitInlinedDirective( 5162 CGF, OMPD_distribute, CodeGenDistribute, /*HasCancel=*/false); 5163 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_teams); 5164 }; 5165 5166 emitCommonOMPTeamsDirective(CGF, S, OMPD_distribute_parallel_for_simd, 5167 CodeGenTeams); 5168 emitPostUpdateForReductionClause(CGF, S, 5169 [](CodeGenFunction &) { return nullptr; }); 5170 } 5171 5172 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction( 5173 CodeGenModule &CGM, StringRef ParentName, 5174 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 5175 // Emit SPMD target teams distribute parallel for simd region as a standalone 5176 // region. 5177 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5178 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 5179 }; 5180 llvm::Function *Fn; 5181 llvm::Constant *Addr; 5182 // Emit target region as a standalone region. 5183 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5184 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5185 assert(Fn && Addr && "Target device function emission failed."); 5186 } 5187 5188 void CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForSimdDirective( 5189 const OMPTargetTeamsDistributeParallelForSimdDirective &S) { 5190 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5191 emitTargetTeamsDistributeParallelForSimdRegion(CGF, S, Action); 5192 }; 5193 emitCommonOMPTargetDirective(*this, S, CodeGen); 5194 } 5195 5196 void CodeGenFunction::EmitOMPCancellationPointDirective( 5197 const OMPCancellationPointDirective &S) { 5198 CGM.getOpenMPRuntime().emitCancellationPointCall(*this, S.getBeginLoc(), 5199 S.getCancelRegion()); 5200 } 5201 5202 void CodeGenFunction::EmitOMPCancelDirective(const OMPCancelDirective &S) { 5203 const Expr *IfCond = nullptr; 5204 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5205 if (C->getNameModifier() == OMPD_unknown || 5206 C->getNameModifier() == OMPD_cancel) { 5207 IfCond = C->getCondition(); 5208 break; 5209 } 5210 } 5211 if (llvm::OpenMPIRBuilder *OMPBuilder = CGM.getOpenMPIRBuilder()) { 5212 // TODO: This check is necessary as we only generate `omp parallel` through 5213 // the OpenMPIRBuilder for now. 5214 if (S.getCancelRegion() == OMPD_parallel) { 5215 llvm::Value *IfCondition = nullptr; 5216 if (IfCond) 5217 IfCondition = EmitScalarExpr(IfCond, 5218 /*IgnoreResultAssign=*/true); 5219 return Builder.restoreIP( 5220 OMPBuilder->CreateCancel(Builder, IfCondition, S.getCancelRegion())); 5221 } 5222 } 5223 5224 CGM.getOpenMPRuntime().emitCancelCall(*this, S.getBeginLoc(), IfCond, 5225 S.getCancelRegion()); 5226 } 5227 5228 CodeGenFunction::JumpDest 5229 CodeGenFunction::getOMPCancelDestination(OpenMPDirectiveKind Kind) { 5230 if (Kind == OMPD_parallel || Kind == OMPD_task || 5231 Kind == OMPD_target_parallel || Kind == OMPD_taskloop || 5232 Kind == OMPD_master_taskloop || Kind == OMPD_parallel_master_taskloop) 5233 return ReturnBlock; 5234 assert(Kind == OMPD_for || Kind == OMPD_section || Kind == OMPD_sections || 5235 Kind == OMPD_parallel_sections || Kind == OMPD_parallel_for || 5236 Kind == OMPD_distribute_parallel_for || 5237 Kind == OMPD_target_parallel_for || 5238 Kind == OMPD_teams_distribute_parallel_for || 5239 Kind == OMPD_target_teams_distribute_parallel_for); 5240 return OMPCancelStack.getExitBlock(); 5241 } 5242 5243 void CodeGenFunction::EmitOMPUseDevicePtrClause( 5244 const OMPClause &NC, OMPPrivateScope &PrivateScope, 5245 const llvm::DenseMap<const ValueDecl *, Address> &CaptureDeviceAddrMap) { 5246 const auto &C = cast<OMPUseDevicePtrClause>(NC); 5247 auto OrigVarIt = C.varlist_begin(); 5248 auto InitIt = C.inits().begin(); 5249 for (const Expr *PvtVarIt : C.private_copies()) { 5250 const auto *OrigVD = cast<VarDecl>(cast<DeclRefExpr>(*OrigVarIt)->getDecl()); 5251 const auto *InitVD = cast<VarDecl>(cast<DeclRefExpr>(*InitIt)->getDecl()); 5252 const auto *PvtVD = cast<VarDecl>(cast<DeclRefExpr>(PvtVarIt)->getDecl()); 5253 5254 // In order to identify the right initializer we need to match the 5255 // declaration used by the mapping logic. In some cases we may get 5256 // OMPCapturedExprDecl that refers to the original declaration. 5257 const ValueDecl *MatchingVD = OrigVD; 5258 if (const auto *OED = dyn_cast<OMPCapturedExprDecl>(MatchingVD)) { 5259 // OMPCapturedExprDecl are used to privative fields of the current 5260 // structure. 5261 const auto *ME = cast<MemberExpr>(OED->getInit()); 5262 assert(isa<CXXThisExpr>(ME->getBase()) && 5263 "Base should be the current struct!"); 5264 MatchingVD = ME->getMemberDecl(); 5265 } 5266 5267 // If we don't have information about the current list item, move on to 5268 // the next one. 5269 auto InitAddrIt = CaptureDeviceAddrMap.find(MatchingVD); 5270 if (InitAddrIt == CaptureDeviceAddrMap.end()) 5271 continue; 5272 5273 bool IsRegistered = PrivateScope.addPrivate(OrigVD, [this, OrigVD, 5274 InitAddrIt, InitVD, 5275 PvtVD]() { 5276 // Initialize the temporary initialization variable with the address we 5277 // get from the runtime library. We have to cast the source address 5278 // because it is always a void *. References are materialized in the 5279 // privatization scope, so the initialization here disregards the fact 5280 // the original variable is a reference. 5281 QualType AddrQTy = 5282 getContext().getPointerType(OrigVD->getType().getNonReferenceType()); 5283 llvm::Type *AddrTy = ConvertTypeForMem(AddrQTy); 5284 Address InitAddr = Builder.CreateBitCast(InitAddrIt->second, AddrTy); 5285 setAddrOfLocalVar(InitVD, InitAddr); 5286 5287 // Emit private declaration, it will be initialized by the value we 5288 // declaration we just added to the local declarations map. 5289 EmitDecl(*PvtVD); 5290 5291 // The initialization variables reached its purpose in the emission 5292 // of the previous declaration, so we don't need it anymore. 5293 LocalDeclMap.erase(InitVD); 5294 5295 // Return the address of the private variable. 5296 return GetAddrOfLocalVar(PvtVD); 5297 }); 5298 assert(IsRegistered && "firstprivate var already registered as private"); 5299 // Silence the warning about unused variable. 5300 (void)IsRegistered; 5301 5302 ++OrigVarIt; 5303 ++InitIt; 5304 } 5305 } 5306 5307 // Generate the instructions for '#pragma omp target data' directive. 5308 void CodeGenFunction::EmitOMPTargetDataDirective( 5309 const OMPTargetDataDirective &S) { 5310 CGOpenMPRuntime::TargetDataInfo Info(/*RequiresDevicePointerInfo=*/true); 5311 5312 // Create a pre/post action to signal the privatization of the device pointer. 5313 // This action can be replaced by the OpenMP runtime code generation to 5314 // deactivate privatization. 5315 bool PrivatizeDevicePointers = false; 5316 class DevicePointerPrivActionTy : public PrePostActionTy { 5317 bool &PrivatizeDevicePointers; 5318 5319 public: 5320 explicit DevicePointerPrivActionTy(bool &PrivatizeDevicePointers) 5321 : PrePostActionTy(), PrivatizeDevicePointers(PrivatizeDevicePointers) {} 5322 void Enter(CodeGenFunction &CGF) override { 5323 PrivatizeDevicePointers = true; 5324 } 5325 }; 5326 DevicePointerPrivActionTy PrivAction(PrivatizeDevicePointers); 5327 5328 auto &&CodeGen = [&S, &Info, &PrivatizeDevicePointers]( 5329 CodeGenFunction &CGF, PrePostActionTy &Action) { 5330 auto &&InnermostCodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5331 CGF.EmitStmt(S.getInnermostCapturedStmt()->getCapturedStmt()); 5332 }; 5333 5334 // Codegen that selects whether to generate the privatization code or not. 5335 auto &&PrivCodeGen = [&S, &Info, &PrivatizeDevicePointers, 5336 &InnermostCodeGen](CodeGenFunction &CGF, 5337 PrePostActionTy &Action) { 5338 RegionCodeGenTy RCG(InnermostCodeGen); 5339 PrivatizeDevicePointers = false; 5340 5341 // Call the pre-action to change the status of PrivatizeDevicePointers if 5342 // needed. 5343 Action.Enter(CGF); 5344 5345 if (PrivatizeDevicePointers) { 5346 OMPPrivateScope PrivateScope(CGF); 5347 // Emit all instances of the use_device_ptr clause. 5348 for (const auto *C : S.getClausesOfKind<OMPUseDevicePtrClause>()) 5349 CGF.EmitOMPUseDevicePtrClause(*C, PrivateScope, 5350 Info.CaptureDeviceAddrMap); 5351 (void)PrivateScope.Privatize(); 5352 RCG(CGF); 5353 } else { 5354 RCG(CGF); 5355 } 5356 }; 5357 5358 // Forward the provided action to the privatization codegen. 5359 RegionCodeGenTy PrivRCG(PrivCodeGen); 5360 PrivRCG.setAction(Action); 5361 5362 // Notwithstanding the body of the region is emitted as inlined directive, 5363 // we don't use an inline scope as changes in the references inside the 5364 // region are expected to be visible outside, so we do not privative them. 5365 OMPLexicalScope Scope(CGF, S); 5366 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_target_data, 5367 PrivRCG); 5368 }; 5369 5370 RegionCodeGenTy RCG(CodeGen); 5371 5372 // If we don't have target devices, don't bother emitting the data mapping 5373 // code. 5374 if (CGM.getLangOpts().OMPTargetTriples.empty()) { 5375 RCG(*this); 5376 return; 5377 } 5378 5379 // Check if we have any if clause associated with the directive. 5380 const Expr *IfCond = nullptr; 5381 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5382 IfCond = C->getCondition(); 5383 5384 // Check if we have any device clause associated with the directive. 5385 const Expr *Device = nullptr; 5386 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5387 Device = C->getDevice(); 5388 5389 // Set the action to signal privatization of device pointers. 5390 RCG.setAction(PrivAction); 5391 5392 // Emit region code. 5393 CGM.getOpenMPRuntime().emitTargetDataCalls(*this, S, IfCond, Device, RCG, 5394 Info); 5395 } 5396 5397 void CodeGenFunction::EmitOMPTargetEnterDataDirective( 5398 const OMPTargetEnterDataDirective &S) { 5399 // If we don't have target devices, don't bother emitting the data mapping 5400 // code. 5401 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5402 return; 5403 5404 // Check if we have any if clause associated with the directive. 5405 const Expr *IfCond = nullptr; 5406 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5407 IfCond = C->getCondition(); 5408 5409 // Check if we have any device clause associated with the directive. 5410 const Expr *Device = nullptr; 5411 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5412 Device = C->getDevice(); 5413 5414 OMPLexicalScope Scope(*this, S, OMPD_task); 5415 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5416 } 5417 5418 void CodeGenFunction::EmitOMPTargetExitDataDirective( 5419 const OMPTargetExitDataDirective &S) { 5420 // If we don't have target devices, don't bother emitting the data mapping 5421 // code. 5422 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5423 return; 5424 5425 // Check if we have any if clause associated with the directive. 5426 const Expr *IfCond = nullptr; 5427 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5428 IfCond = C->getCondition(); 5429 5430 // Check if we have any device clause associated with the directive. 5431 const Expr *Device = nullptr; 5432 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5433 Device = C->getDevice(); 5434 5435 OMPLexicalScope Scope(*this, S, OMPD_task); 5436 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5437 } 5438 5439 static void emitTargetParallelRegion(CodeGenFunction &CGF, 5440 const OMPTargetParallelDirective &S, 5441 PrePostActionTy &Action) { 5442 // Get the captured statement associated with the 'parallel' region. 5443 const CapturedStmt *CS = S.getCapturedStmt(OMPD_parallel); 5444 Action.Enter(CGF); 5445 auto &&CodeGen = [&S, CS](CodeGenFunction &CGF, PrePostActionTy &Action) { 5446 Action.Enter(CGF); 5447 CodeGenFunction::OMPPrivateScope PrivateScope(CGF); 5448 (void)CGF.EmitOMPFirstprivateClause(S, PrivateScope); 5449 CGF.EmitOMPPrivateClause(S, PrivateScope); 5450 CGF.EmitOMPReductionClauseInit(S, PrivateScope); 5451 (void)PrivateScope.Privatize(); 5452 if (isOpenMPTargetExecutionDirective(S.getDirectiveKind())) 5453 CGF.CGM.getOpenMPRuntime().adjustTargetSpecificDataForLambdas(CGF, S); 5454 // TODO: Add support for clauses. 5455 CGF.EmitStmt(CS->getCapturedStmt()); 5456 CGF.EmitOMPReductionClauseFinal(S, /*ReductionKind=*/OMPD_parallel); 5457 }; 5458 emitCommonOMPParallelDirective(CGF, S, OMPD_parallel, CodeGen, 5459 emitEmptyBoundParameters); 5460 emitPostUpdateForReductionClause(CGF, S, 5461 [](CodeGenFunction &) { return nullptr; }); 5462 } 5463 5464 void CodeGenFunction::EmitOMPTargetParallelDeviceFunction( 5465 CodeGenModule &CGM, StringRef ParentName, 5466 const OMPTargetParallelDirective &S) { 5467 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5468 emitTargetParallelRegion(CGF, S, Action); 5469 }; 5470 llvm::Function *Fn; 5471 llvm::Constant *Addr; 5472 // Emit target region as a standalone region. 5473 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5474 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5475 assert(Fn && Addr && "Target device function emission failed."); 5476 } 5477 5478 void CodeGenFunction::EmitOMPTargetParallelDirective( 5479 const OMPTargetParallelDirective &S) { 5480 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5481 emitTargetParallelRegion(CGF, S, Action); 5482 }; 5483 emitCommonOMPTargetDirective(*this, S, CodeGen); 5484 } 5485 5486 static void emitTargetParallelForRegion(CodeGenFunction &CGF, 5487 const OMPTargetParallelForDirective &S, 5488 PrePostActionTy &Action) { 5489 Action.Enter(CGF); 5490 // Emit directive as a combined directive that consists of two implicit 5491 // directives: 'parallel' with 'for' directive. 5492 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5493 Action.Enter(CGF); 5494 CodeGenFunction::OMPCancelStackRAII CancelRegion( 5495 CGF, OMPD_target_parallel_for, S.hasCancel()); 5496 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 5497 emitDispatchForLoopBounds); 5498 }; 5499 emitCommonOMPParallelDirective(CGF, S, OMPD_for, CodeGen, 5500 emitEmptyBoundParameters); 5501 } 5502 5503 void CodeGenFunction::EmitOMPTargetParallelForDeviceFunction( 5504 CodeGenModule &CGM, StringRef ParentName, 5505 const OMPTargetParallelForDirective &S) { 5506 // Emit SPMD target parallel for region as a standalone region. 5507 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5508 emitTargetParallelForRegion(CGF, S, Action); 5509 }; 5510 llvm::Function *Fn; 5511 llvm::Constant *Addr; 5512 // Emit target region as a standalone region. 5513 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5514 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5515 assert(Fn && Addr && "Target device function emission failed."); 5516 } 5517 5518 void CodeGenFunction::EmitOMPTargetParallelForDirective( 5519 const OMPTargetParallelForDirective &S) { 5520 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5521 emitTargetParallelForRegion(CGF, S, Action); 5522 }; 5523 emitCommonOMPTargetDirective(*this, S, CodeGen); 5524 } 5525 5526 static void 5527 emitTargetParallelForSimdRegion(CodeGenFunction &CGF, 5528 const OMPTargetParallelForSimdDirective &S, 5529 PrePostActionTy &Action) { 5530 Action.Enter(CGF); 5531 // Emit directive as a combined directive that consists of two implicit 5532 // directives: 'parallel' with 'for' directive. 5533 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5534 Action.Enter(CGF); 5535 CGF.EmitOMPWorksharingLoop(S, S.getEnsureUpperBound(), emitForLoopBounds, 5536 emitDispatchForLoopBounds); 5537 }; 5538 emitCommonOMPParallelDirective(CGF, S, OMPD_simd, CodeGen, 5539 emitEmptyBoundParameters); 5540 } 5541 5542 void CodeGenFunction::EmitOMPTargetParallelForSimdDeviceFunction( 5543 CodeGenModule &CGM, StringRef ParentName, 5544 const OMPTargetParallelForSimdDirective &S) { 5545 // Emit SPMD target parallel for region as a standalone region. 5546 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5547 emitTargetParallelForSimdRegion(CGF, S, Action); 5548 }; 5549 llvm::Function *Fn; 5550 llvm::Constant *Addr; 5551 // Emit target region as a standalone region. 5552 CGM.getOpenMPRuntime().emitTargetOutlinedFunction( 5553 S, ParentName, Fn, Addr, /*IsOffloadEntry=*/true, CodeGen); 5554 assert(Fn && Addr && "Target device function emission failed."); 5555 } 5556 5557 void CodeGenFunction::EmitOMPTargetParallelForSimdDirective( 5558 const OMPTargetParallelForSimdDirective &S) { 5559 auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5560 emitTargetParallelForSimdRegion(CGF, S, Action); 5561 }; 5562 emitCommonOMPTargetDirective(*this, S, CodeGen); 5563 } 5564 5565 /// Emit a helper variable and return corresponding lvalue. 5566 static void mapParam(CodeGenFunction &CGF, const DeclRefExpr *Helper, 5567 const ImplicitParamDecl *PVD, 5568 CodeGenFunction::OMPPrivateScope &Privates) { 5569 const auto *VDecl = cast<VarDecl>(Helper->getDecl()); 5570 Privates.addPrivate(VDecl, 5571 [&CGF, PVD]() { return CGF.GetAddrOfLocalVar(PVD); }); 5572 } 5573 5574 void CodeGenFunction::EmitOMPTaskLoopBasedDirective(const OMPLoopDirective &S) { 5575 assert(isOpenMPTaskLoopDirective(S.getDirectiveKind())); 5576 // Emit outlined function for task construct. 5577 const CapturedStmt *CS = S.getCapturedStmt(OMPD_taskloop); 5578 Address CapturedStruct = Address::invalid(); 5579 { 5580 OMPLexicalScope Scope(*this, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 5581 CapturedStruct = GenerateCapturedStmtArgument(*CS); 5582 } 5583 QualType SharedsTy = getContext().getRecordType(CS->getCapturedRecordDecl()); 5584 const Expr *IfCond = nullptr; 5585 for (const auto *C : S.getClausesOfKind<OMPIfClause>()) { 5586 if (C->getNameModifier() == OMPD_unknown || 5587 C->getNameModifier() == OMPD_taskloop) { 5588 IfCond = C->getCondition(); 5589 break; 5590 } 5591 } 5592 5593 OMPTaskDataTy Data; 5594 // Check if taskloop must be emitted without taskgroup. 5595 Data.Nogroup = S.getSingleClause<OMPNogroupClause>(); 5596 // TODO: Check if we should emit tied or untied task. 5597 Data.Tied = true; 5598 // Set scheduling for taskloop 5599 if (const auto* Clause = S.getSingleClause<OMPGrainsizeClause>()) { 5600 // grainsize clause 5601 Data.Schedule.setInt(/*IntVal=*/false); 5602 Data.Schedule.setPointer(EmitScalarExpr(Clause->getGrainsize())); 5603 } else if (const auto* Clause = S.getSingleClause<OMPNumTasksClause>()) { 5604 // num_tasks clause 5605 Data.Schedule.setInt(/*IntVal=*/true); 5606 Data.Schedule.setPointer(EmitScalarExpr(Clause->getNumTasks())); 5607 } 5608 5609 auto &&BodyGen = [CS, &S](CodeGenFunction &CGF, PrePostActionTy &) { 5610 // if (PreCond) { 5611 // for (IV in 0..LastIteration) BODY; 5612 // <Final counter/linear vars updates>; 5613 // } 5614 // 5615 5616 // Emit: if (PreCond) - begin. 5617 // If the condition constant folds and can be elided, avoid emitting the 5618 // whole loop. 5619 bool CondConstant; 5620 llvm::BasicBlock *ContBlock = nullptr; 5621 OMPLoopScope PreInitScope(CGF, S); 5622 if (CGF.ConstantFoldsToSimpleInteger(S.getPreCond(), CondConstant)) { 5623 if (!CondConstant) 5624 return; 5625 } else { 5626 llvm::BasicBlock *ThenBlock = CGF.createBasicBlock("taskloop.if.then"); 5627 ContBlock = CGF.createBasicBlock("taskloop.if.end"); 5628 emitPreCond(CGF, S, S.getPreCond(), ThenBlock, ContBlock, 5629 CGF.getProfileCount(&S)); 5630 CGF.EmitBlock(ThenBlock); 5631 CGF.incrementProfileCounter(&S); 5632 } 5633 5634 (void)CGF.EmitOMPLinearClauseInit(S); 5635 5636 OMPPrivateScope LoopScope(CGF); 5637 // Emit helper vars inits. 5638 enum { LowerBound = 5, UpperBound, Stride, LastIter }; 5639 auto *I = CS->getCapturedDecl()->param_begin(); 5640 auto *LBP = std::next(I, LowerBound); 5641 auto *UBP = std::next(I, UpperBound); 5642 auto *STP = std::next(I, Stride); 5643 auto *LIP = std::next(I, LastIter); 5644 mapParam(CGF, cast<DeclRefExpr>(S.getLowerBoundVariable()), *LBP, 5645 LoopScope); 5646 mapParam(CGF, cast<DeclRefExpr>(S.getUpperBoundVariable()), *UBP, 5647 LoopScope); 5648 mapParam(CGF, cast<DeclRefExpr>(S.getStrideVariable()), *STP, LoopScope); 5649 mapParam(CGF, cast<DeclRefExpr>(S.getIsLastIterVariable()), *LIP, 5650 LoopScope); 5651 CGF.EmitOMPPrivateLoopCounters(S, LoopScope); 5652 CGF.EmitOMPLinearClause(S, LoopScope); 5653 bool HasLastprivateClause = CGF.EmitOMPLastprivateClauseInit(S, LoopScope); 5654 (void)LoopScope.Privatize(); 5655 // Emit the loop iteration variable. 5656 const Expr *IVExpr = S.getIterationVariable(); 5657 const auto *IVDecl = cast<VarDecl>(cast<DeclRefExpr>(IVExpr)->getDecl()); 5658 CGF.EmitVarDecl(*IVDecl); 5659 CGF.EmitIgnoredExpr(S.getInit()); 5660 5661 // Emit the iterations count variable. 5662 // If it is not a variable, Sema decided to calculate iterations count on 5663 // each iteration (e.g., it is foldable into a constant). 5664 if (const auto *LIExpr = dyn_cast<DeclRefExpr>(S.getLastIteration())) { 5665 CGF.EmitVarDecl(*cast<VarDecl>(LIExpr->getDecl())); 5666 // Emit calculation of the iterations count. 5667 CGF.EmitIgnoredExpr(S.getCalcLastIteration()); 5668 } 5669 5670 { 5671 OMPLexicalScope Scope(CGF, S, OMPD_taskloop, /*EmitPreInitStmt=*/false); 5672 emitCommonSimdLoop( 5673 CGF, S, 5674 [&S](CodeGenFunction &CGF, PrePostActionTy &) { 5675 if (isOpenMPSimdDirective(S.getDirectiveKind())) 5676 CGF.EmitOMPSimdInit(S); 5677 }, 5678 [&S, &LoopScope](CodeGenFunction &CGF, PrePostActionTy &) { 5679 CGF.EmitOMPInnerLoop( 5680 S, LoopScope.requiresCleanups(), S.getCond(), S.getInc(), 5681 [&S](CodeGenFunction &CGF) { 5682 CGF.EmitOMPLoopBody(S, CodeGenFunction::JumpDest()); 5683 CGF.EmitStopPoint(&S); 5684 }, 5685 [](CodeGenFunction &) {}); 5686 }); 5687 } 5688 // Emit: if (PreCond) - end. 5689 if (ContBlock) { 5690 CGF.EmitBranch(ContBlock); 5691 CGF.EmitBlock(ContBlock, true); 5692 } 5693 // Emit final copy of the lastprivate variables if IsLastIter != 0. 5694 if (HasLastprivateClause) { 5695 CGF.EmitOMPLastprivateClauseFinal( 5696 S, isOpenMPSimdDirective(S.getDirectiveKind()), 5697 CGF.Builder.CreateIsNotNull(CGF.EmitLoadOfScalar( 5698 CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 5699 (*LIP)->getType(), S.getBeginLoc()))); 5700 } 5701 CGF.EmitOMPLinearClauseFinal(S, [LIP, &S](CodeGenFunction &CGF) { 5702 return CGF.Builder.CreateIsNotNull( 5703 CGF.EmitLoadOfScalar(CGF.GetAddrOfLocalVar(*LIP), /*Volatile=*/false, 5704 (*LIP)->getType(), S.getBeginLoc())); 5705 }); 5706 }; 5707 auto &&TaskGen = [&S, SharedsTy, CapturedStruct, 5708 IfCond](CodeGenFunction &CGF, llvm::Function *OutlinedFn, 5709 const OMPTaskDataTy &Data) { 5710 auto &&CodeGen = [&S, OutlinedFn, SharedsTy, CapturedStruct, IfCond, 5711 &Data](CodeGenFunction &CGF, PrePostActionTy &) { 5712 OMPLoopScope PreInitScope(CGF, S); 5713 CGF.CGM.getOpenMPRuntime().emitTaskLoopCall(CGF, S.getBeginLoc(), S, 5714 OutlinedFn, SharedsTy, 5715 CapturedStruct, IfCond, Data); 5716 }; 5717 CGF.CGM.getOpenMPRuntime().emitInlinedDirective(CGF, OMPD_taskloop, 5718 CodeGen); 5719 }; 5720 if (Data.Nogroup) { 5721 EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, Data); 5722 } else { 5723 CGM.getOpenMPRuntime().emitTaskgroupRegion( 5724 *this, 5725 [&S, &BodyGen, &TaskGen, &Data](CodeGenFunction &CGF, 5726 PrePostActionTy &Action) { 5727 Action.Enter(CGF); 5728 CGF.EmitOMPTaskBasedDirective(S, OMPD_taskloop, BodyGen, TaskGen, 5729 Data); 5730 }, 5731 S.getBeginLoc()); 5732 } 5733 } 5734 5735 void CodeGenFunction::EmitOMPTaskLoopDirective(const OMPTaskLoopDirective &S) { 5736 auto LPCRegion = 5737 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5738 EmitOMPTaskLoopBasedDirective(S); 5739 } 5740 5741 void CodeGenFunction::EmitOMPTaskLoopSimdDirective( 5742 const OMPTaskLoopSimdDirective &S) { 5743 auto LPCRegion = 5744 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5745 OMPLexicalScope Scope(*this, S); 5746 EmitOMPTaskLoopBasedDirective(S); 5747 } 5748 5749 void CodeGenFunction::EmitOMPMasterTaskLoopDirective( 5750 const OMPMasterTaskLoopDirective &S) { 5751 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5752 Action.Enter(CGF); 5753 EmitOMPTaskLoopBasedDirective(S); 5754 }; 5755 auto LPCRegion = 5756 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5757 OMPLexicalScope Scope(*this, S, llvm::None, /*EmitPreInitStmt=*/false); 5758 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 5759 } 5760 5761 void CodeGenFunction::EmitOMPMasterTaskLoopSimdDirective( 5762 const OMPMasterTaskLoopSimdDirective &S) { 5763 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5764 Action.Enter(CGF); 5765 EmitOMPTaskLoopBasedDirective(S); 5766 }; 5767 auto LPCRegion = 5768 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5769 OMPLexicalScope Scope(*this, S); 5770 CGM.getOpenMPRuntime().emitMasterRegion(*this, CodeGen, S.getBeginLoc()); 5771 } 5772 5773 void CodeGenFunction::EmitOMPParallelMasterTaskLoopDirective( 5774 const OMPParallelMasterTaskLoopDirective &S) { 5775 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5776 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 5777 PrePostActionTy &Action) { 5778 Action.Enter(CGF); 5779 CGF.EmitOMPTaskLoopBasedDirective(S); 5780 }; 5781 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 5782 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 5783 S.getBeginLoc()); 5784 }; 5785 auto LPCRegion = 5786 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5787 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop, CodeGen, 5788 emitEmptyBoundParameters); 5789 } 5790 5791 void CodeGenFunction::EmitOMPParallelMasterTaskLoopSimdDirective( 5792 const OMPParallelMasterTaskLoopSimdDirective &S) { 5793 auto &&CodeGen = [this, &S](CodeGenFunction &CGF, PrePostActionTy &Action) { 5794 auto &&TaskLoopCodeGen = [&S](CodeGenFunction &CGF, 5795 PrePostActionTy &Action) { 5796 Action.Enter(CGF); 5797 CGF.EmitOMPTaskLoopBasedDirective(S); 5798 }; 5799 OMPLexicalScope Scope(CGF, S, OMPD_parallel, /*EmitPreInitStmt=*/false); 5800 CGM.getOpenMPRuntime().emitMasterRegion(CGF, TaskLoopCodeGen, 5801 S.getBeginLoc()); 5802 }; 5803 auto LPCRegion = 5804 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, S); 5805 emitCommonOMPParallelDirective(*this, S, OMPD_master_taskloop_simd, CodeGen, 5806 emitEmptyBoundParameters); 5807 } 5808 5809 // Generate the instructions for '#pragma omp target update' directive. 5810 void CodeGenFunction::EmitOMPTargetUpdateDirective( 5811 const OMPTargetUpdateDirective &S) { 5812 // If we don't have target devices, don't bother emitting the data mapping 5813 // code. 5814 if (CGM.getLangOpts().OMPTargetTriples.empty()) 5815 return; 5816 5817 // Check if we have any if clause associated with the directive. 5818 const Expr *IfCond = nullptr; 5819 if (const auto *C = S.getSingleClause<OMPIfClause>()) 5820 IfCond = C->getCondition(); 5821 5822 // Check if we have any device clause associated with the directive. 5823 const Expr *Device = nullptr; 5824 if (const auto *C = S.getSingleClause<OMPDeviceClause>()) 5825 Device = C->getDevice(); 5826 5827 OMPLexicalScope Scope(*this, S, OMPD_task); 5828 CGM.getOpenMPRuntime().emitTargetDataStandAloneCall(*this, S, IfCond, Device); 5829 } 5830 5831 void CodeGenFunction::EmitSimpleOMPExecutableDirective( 5832 const OMPExecutableDirective &D) { 5833 if (!D.hasAssociatedStmt() || !D.getAssociatedStmt()) 5834 return; 5835 auto &&CodeGen = [&D](CodeGenFunction &CGF, PrePostActionTy &Action) { 5836 OMPPrivateScope GlobalsScope(CGF); 5837 if (isOpenMPTaskingDirective(D.getDirectiveKind())) { 5838 // Capture global firstprivates to avoid crash. 5839 for (const auto *C : D.getClausesOfKind<OMPFirstprivateClause>()) { 5840 for (const Expr *Ref : C->varlists()) { 5841 const auto *DRE = cast<DeclRefExpr>(Ref->IgnoreParenImpCasts()); 5842 if (!DRE) 5843 continue; 5844 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 5845 if (!VD || VD->hasLocalStorage()) 5846 continue; 5847 if (!CGF.LocalDeclMap.count(VD)) { 5848 LValue GlobLVal = CGF.EmitLValue(Ref); 5849 GlobalsScope.addPrivate( 5850 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 5851 } 5852 } 5853 } 5854 } 5855 if (isOpenMPSimdDirective(D.getDirectiveKind())) { 5856 (void)GlobalsScope.Privatize(); 5857 emitOMPSimdRegion(CGF, cast<OMPLoopDirective>(D), Action); 5858 } else { 5859 if (const auto *LD = dyn_cast<OMPLoopDirective>(&D)) { 5860 for (const Expr *E : LD->counters()) { 5861 const auto *VD = cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl()); 5862 if (!VD->hasLocalStorage() && !CGF.LocalDeclMap.count(VD)) { 5863 LValue GlobLVal = CGF.EmitLValue(E); 5864 GlobalsScope.addPrivate( 5865 VD, [&GlobLVal, &CGF]() { return GlobLVal.getAddress(CGF); }); 5866 } 5867 if (isa<OMPCapturedExprDecl>(VD)) { 5868 // Emit only those that were not explicitly referenced in clauses. 5869 if (!CGF.LocalDeclMap.count(VD)) 5870 CGF.EmitVarDecl(*VD); 5871 } 5872 } 5873 for (const auto *C : D.getClausesOfKind<OMPOrderedClause>()) { 5874 if (!C->getNumForLoops()) 5875 continue; 5876 for (unsigned I = LD->getCollapsedNumber(), 5877 E = C->getLoopNumIterations().size(); 5878 I < E; ++I) { 5879 if (const auto *VD = dyn_cast<OMPCapturedExprDecl>( 5880 cast<DeclRefExpr>(C->getLoopCounter(I))->getDecl())) { 5881 // Emit only those that were not explicitly referenced in clauses. 5882 if (!CGF.LocalDeclMap.count(VD)) 5883 CGF.EmitVarDecl(*VD); 5884 } 5885 } 5886 } 5887 } 5888 (void)GlobalsScope.Privatize(); 5889 CGF.EmitStmt(D.getInnermostCapturedStmt()->getCapturedStmt()); 5890 } 5891 }; 5892 { 5893 auto LPCRegion = 5894 CGOpenMPRuntime::LastprivateConditionalRAII::disable(*this, D); 5895 OMPSimdLexicalScope Scope(*this, D); 5896 CGM.getOpenMPRuntime().emitInlinedDirective( 5897 *this, 5898 isOpenMPSimdDirective(D.getDirectiveKind()) ? OMPD_simd 5899 : D.getDirectiveKind(), 5900 CodeGen); 5901 } 5902 // Check for outer lastprivate conditional update. 5903 checkForLastprivateConditionalUpdate(*this, D); 5904 } 5905