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