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