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