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